From 139f15ac88cc4cb3df55fccb5e99e07f81c02cd4 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 18:29:46 +0100 Subject: [PATCH 01/30] ci: cache the Linux compiler output with ccache --- .github/workflows/build_bin.yml | 37 +++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index fed45a44b..a4e8097ff 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -252,6 +252,7 @@ jobs: # 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 \ + ccache \ libasound2-dev \ libpulse-dev \ libpipewire-0.3-dev \ @@ -309,11 +310,34 @@ jobs: cmake --version python --version + # The compiler cache (ccache), one per variant. Only the runs on staging and master save it (the step after the + # build); a pull request takes the newest one of its variant, and so recompiles just what it changed. A pull + # request can read the caches of its base branch and of the default branch, not those of other pull requests. + # The compiler version is in the key, so a new GCC of the runner image starts a cache of its own. + - name: Compiler cache key + id: ccache-key + run: echo "gcc=$(g++ -dumpfullversion)" >> "$GITHUB_OUTPUT" + + - name: Restore the compiler cache + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/ccache + key: ccache-linux-${{ matrix.variant.suffix }}-gcc${{ steps.ccache-key.outputs.gcc }}-${{ github.sha }} + restore-keys: | + ccache-linux-${{ matrix.variant.suffix }}-gcc${{ steps.ccache-key.outputs.gcc }}- + ccache-linux-${{ matrix.variant.suffix }}- + - name: Configure + env: + CCACHE_DIR: ${{ runner.temp }}/ccache + CCACHE_MAXSIZE: 500M run: | + ccache --zero-stats cmake \ -S . \ -B build \ + -DCMAKE_C_COMPILER_LAUNCHER=ccache \ + -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ -DCMAKE_BUILD_TYPE="${CONFIG_LINUX}" \ -DWITH_BETTER_RENDERER=OFF \ -DWITH_ZMQ=OFF \ @@ -323,11 +347,24 @@ jobs: -DPython3_EXECUTABLE="${{ steps.python.outputs.python-path }}" \ -DCMAKE_CXX_FLAGS="-Wno-attributes -fno-inline-functions-called-once" + # CCACHE_BASEDIR makes the paths relative, so a cache made on another checkout path still hits - name: Build + env: + CCACHE_DIR: ${{ runner.temp }}/ccache + CCACHE_MAXSIZE: 500M + CCACHE_BASEDIR: ${{ github.workspace }} run: | cmake \ --build build \ --parallel "$(nproc)" + ccache --show-stats + + - name: Save the compiler cache + if: ${{ !cancelled() && github.event_name == 'push' && (github.ref == 'refs/heads/staging' || github.ref == 'refs/heads/master') }} + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/ccache + key: ccache-linux-${{ matrix.variant.suffix }}-gcc${{ steps.ccache-key.outputs.gcc }}-${{ github.sha }} # the build copies the shared libraries next to the game (CMake_modules/bundle_runtime_libs.cmake) and the # game looks for them there first ($ORIGIN): each one it loads from outside build/bin has to be one of the system From b64d4dab1a0f54a16e5886d4924b27ade78a078b Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 18:30:21 +0100 Subject: [PATCH 02/30] ci: build only the AVX2 variants on pull requests --- .github/workflows/build_bin.yml | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index a4e8097ff..a3cd2e5d1 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -45,13 +45,9 @@ jobs: strategy: fail-fast: false matrix: - variant: - - name: "AVX2" - suffix: "avx2" - cmake_flags: "-DENABLE_AVX2=ON" - - name: "No AVX2" - suffix: "noavx2" - cmake_flags: "-DENABLE_AVX2=OFF" + # a pull request builds the AVX2 variant only; the variant without AVX2 (the same sources, one compiler + # switch) is built by the pushes to the branches and by a manual run + variant: ${{ fromJSON(github.event_name == 'pull_request' && '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"}]' || '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"},{"name":"No AVX2","suffix":"noavx2","cmake_flags":"-DENABLE_AVX2=OFF"}]') }} steps: - name: Checkout repository @@ -215,13 +211,9 @@ jobs: strategy: fail-fast: false matrix: - variant: - - name: "AVX2" - suffix: "avx2" - cmake_flags: "-DENABLE_AVX2=ON" - - name: "No AVX2" - suffix: "noavx2" - cmake_flags: "-DENABLE_AVX2=OFF" + # a pull request builds the AVX2 variant only; the variant without AVX2 (the same sources, one compiler + # switch) is built by the pushes to the branches and by a manual run + variant: ${{ fromJSON(github.event_name == 'pull_request' && '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"}]' || '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"},{"name":"No AVX2","suffix":"noavx2","cmake_flags":"-DENABLE_AVX2=OFF"}]') }} steps: - name: Checkout repository From dc4fbb56f4493427d9e21145f4e08b0fe111cd45 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 20 Nov 2026 18:33:03 +0100 Subject: [PATCH 03/30] ci: skip the coverage build for documentation-only pull requests --- .github/workflows/coverage.yml | 40 ++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index d2f00bccd..3a05010f2 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -28,8 +28,48 @@ concurrency: cancel-in-progress: true jobs: + # A pull request that changes only documentation doesn't need the coverage build. The check is a job-level + # condition, not `paths-ignore` on the trigger: a workflow that doesn't start leaves a required check "pending" + # for ever, while a skipped job (its name is fixed) counts as passed. A push, and anything this step can't + # decide, runs the build. + changes: + name: Which files changed + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + pull-requests: read + outputs: + code: ${{ steps.files.outputs.code }} + steps: + - name: List the changed files + id: files + env: + GH_TOKEN: ${{ github.token }} + EVENT_NAME: ${{ github.event_name }} + REPO: ${{ github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + if [ "$EVENT_NAME" != pull_request ]; then + echo "code=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + if ! files="$(gh api --paginate "repos/$REPO/pulls/$PR_NUMBER/files" --jq '.[].filename')" || [ -z "$files" ]; then + echo "The list of changed files is not available, building." + echo "code=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + # what is not documentation: *.md, docs/ and LICENSE (not *.txt: CMakeLists.txt is code) + if printf '%s\n' "$files" | grep -Evq '(\.md$|^docs/|^LICENSE)'; then + echo "code=true" >> "$GITHUB_OUTPUT" + else + echo "Only documentation changed, the coverage build is skipped." + echo "code=false" >> "$GITHUB_OUTPUT" + fi + coverage: name: Unit test coverage (GCC) + needs: changes + if: needs.changes.outputs.code == 'true' runs-on: ubuntu-24.04 timeout-minutes: 60 permissions: From b9e5ec51a83f5fd5118db654544c245b7f498150 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 22 Nov 2026 19:17:59 +0100 Subject: [PATCH 04/30] ci: ccache through the precompiled header, both variants for forks, renamed files counted - ccache caches the files built with the precompiled header (stdafx.h) only with CCACHE_SLOPPINESS pch_defines,time_macros (plus the include file times); without it every such file was compiled in full while the cache was still restored and saved - a pull request from a fork has no push run here, so it builds the variant without AVX2 too; a branch of this repository still builds only the AVX2 one - the docs-only check also counts the old name of a renamed file, so moving code out to docs/ or a .md name doesn't skip the coverage build - no fallback to the cache of another GCC, which ccache can't use Review of maj00r on #434. --- .github/workflows/build_bin.yml | 24 ++++++++++++++++-------- .github/workflows/coverage.yml | 2 +- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index a3cd2e5d1..f0aad4891 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -45,9 +45,10 @@ jobs: strategy: fail-fast: false matrix: - # a pull request builds the AVX2 variant only; the variant without AVX2 (the same sources, one compiler - # switch) is built by the pushes to the branches and by a manual run - variant: ${{ fromJSON(github.event_name == 'pull_request' && '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"}]' || '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"},{"name":"No AVX2","suffix":"noavx2","cmake_flags":"-DENABLE_AVX2=OFF"}]') }} + # a pull request from a branch of this repository builds the AVX2 variant only; the variant without AVX2 + # (the same sources, one compiler switch) is built by the push of that branch, by the pushes to staging + # and master and by a manual run. a pull request from a fork has no push run here, so it builds both + variant: ${{ fromJSON(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"}]' || '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"},{"name":"No AVX2","suffix":"noavx2","cmake_flags":"-DENABLE_AVX2=OFF"}]') }} steps: - name: Checkout repository @@ -211,9 +212,10 @@ jobs: strategy: fail-fast: false matrix: - # a pull request builds the AVX2 variant only; the variant without AVX2 (the same sources, one compiler - # switch) is built by the pushes to the branches and by a manual run - variant: ${{ fromJSON(github.event_name == 'pull_request' && '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"}]' || '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"},{"name":"No AVX2","suffix":"noavx2","cmake_flags":"-DENABLE_AVX2=OFF"}]') }} + # a pull request from a branch of this repository builds the AVX2 variant only; the variant without AVX2 + # (the same sources, one compiler switch) is built by the push of that branch, by the pushes to staging + # and master and by a manual run. a pull request from a fork has no push run here, so it builds both + variant: ${{ fromJSON(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"}]' || '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"},{"name":"No AVX2","suffix":"noavx2","cmake_flags":"-DENABLE_AVX2=OFF"}]') }} steps: - name: Checkout repository @@ -305,7 +307,8 @@ jobs: # The compiler cache (ccache), one per variant. Only the runs on staging and master save it (the step after the # build); a pull request takes the newest one of its variant, and so recompiles just what it changed. A pull # request can read the caches of its base branch and of the default branch, not those of other pull requests. - # The compiler version is in the key, so a new GCC of the runner image starts a cache of its own. + # The compiler version is in the key, so a new GCC of the runner image starts a cache of its own, with no + # fallback to the cache of the old one, which ccache couldn't use (the compiler is part of its hash). - name: Compiler cache key id: ccache-key run: echo "gcc=$(g++ -dumpfullversion)" >> "$GITHUB_OUTPUT" @@ -317,12 +320,14 @@ jobs: key: ccache-linux-${{ matrix.variant.suffix }}-gcc${{ steps.ccache-key.outputs.gcc }}-${{ github.sha }} restore-keys: | ccache-linux-${{ matrix.variant.suffix }}-gcc${{ steps.ccache-key.outputs.gcc }}- - ccache-linux-${{ matrix.variant.suffix }}- - name: Configure env: CCACHE_DIR: ${{ runner.temp }}/ccache CCACHE_MAXSIZE: 500M + # the game and eu07_core use a precompiled header (stdafx.h): ccache caches such compilations only with + # this sloppiness, else it compiles every file in full + CCACHE_SLOPPINESS: pch_defines,time_macros,include_file_mtime,include_file_ctime run: | ccache --zero-stats cmake \ @@ -345,6 +350,9 @@ jobs: CCACHE_DIR: ${{ runner.temp }}/ccache CCACHE_MAXSIZE: 500M CCACHE_BASEDIR: ${{ github.workspace }} + # the game and eu07_core use a precompiled header (stdafx.h): ccache caches such compilations only with + # this sloppiness, else it compiles every file in full + CCACHE_SLOPPINESS: pch_defines,time_macros,include_file_mtime,include_file_ctime run: | cmake \ --build build \ diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 3a05010f2..dbd79eee8 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -53,7 +53,7 @@ jobs: echo "code=true" >> "$GITHUB_OUTPUT" exit 0 fi - if ! files="$(gh api --paginate "repos/$REPO/pulls/$PR_NUMBER/files" --jq '.[].filename')" || [ -z "$files" ]; then + if ! files="$(gh api --paginate "repos/$REPO/pulls/$PR_NUMBER/files" --jq '.[] | .filename, (.previous_filename // empty)')" || [ -z "$files" ]; then echo "The list of changed files is not available, building." echo "code=true" >> "$GITHUB_OUTPUT" exit 0 From e6611341de196056aacd404bd75df9cda7ac7ae7 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Wed, 25 Nov 2026 02:21:38 +0100 Subject: [PATCH 05/30] ci: a saved compiler cache replaces the older ones of its branch Every push to staging or master saved a new cache key of up to 0.5 GB and nothing deleted the old ones, so master alone would pass the 10 GB of the repository in a week and push out the small caches. The Linux job now deletes the older ccache entries of its branch and variant right after a save (actions: write on that job). The comments say a feature branch push hits only master's cache, and that the No AVX2 jobs of a pull request never run, so they can't be a required check. --- .github/workflows/build_bin.yml | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index f0aad4891..b44a71590 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -47,7 +47,8 @@ jobs: matrix: # a pull request from a branch of this repository builds the AVX2 variant only; the variant without AVX2 # (the same sources, one compiler switch) is built by the push of that branch, by the pushes to staging - # and master and by a manual run. a pull request from a fork has no push run here, so it builds both + # and master and by a manual run. a pull request from a fork has no push run here, so it builds both. + # so the "No AVX2" jobs of a pull request of this repository never run: don't make them a required check variant: ${{ fromJSON(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"}]' || '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"},{"name":"No AVX2","suffix":"noavx2","cmake_flags":"-DENABLE_AVX2=OFF"}]') }} steps: @@ -204,6 +205,10 @@ jobs: linux: name: Linux x64 / GCC / ${{ matrix.variant.name }} runs-on: ubuntu-24.04 + # actions: write only to delete the older compiler caches after a save (the step after "Save the compiler cache") + permissions: + contents: read + actions: write # see the notes above the windows job: two variants, each with a concurrency group of its own concurrency: group: ${{ github.workflow }}-linux-${{ matrix.variant.suffix }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} @@ -305,8 +310,10 @@ jobs: python --version # The compiler cache (ccache), one per variant. Only the runs on staging and master save it (the step after the - # build); a pull request takes the newest one of its variant, and so recompiles just what it changed. A pull - # request can read the caches of its base branch and of the default branch, not those of other pull requests. + # build) and delete their older ones; a pull request takes the newest one of its variant, and so recompiles just + # what it changed. A pull request can read the caches of its base branch and of the default branch, not those of + # other pull requests. A push of another branch can read only master's, so it hits only as far as the branch + # still matches master. # The compiler version is in the key, so a new GCC of the runner image starts a cache of its own, with no # fallback to the cache of the old one, which ccache couldn't use (the compiler is part of its hash). - name: Compiler cache key @@ -360,12 +367,29 @@ jobs: ccache --show-stats - name: Save the compiler cache + id: ccache-save if: ${{ !cancelled() && github.event_name == 'push' && (github.ref == 'refs/heads/staging' || github.ref == 'refs/heads/master') }} uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/ccache key: ccache-linux-${{ matrix.variant.suffix }}-gcc${{ steps.ccache-key.outputs.gcc }}-${{ github.sha }} + # a cache can't be written over, so every save above is a new key of up to 0.5 GB. the older ones of this branch + # and variant (of any GCC) go right after it, or they'd fill the 10 GB of the repository and push out the small + # caches (audio-dlls-*, apt-*). a failed delete only leaves the old cache to the eviction + - name: Delete the older compiler caches + if: ${{ !cancelled() && steps.ccache-save.outcome == 'success' }} + env: + GH_TOKEN: ${{ github.token }} + PREFIX: ccache-linux-${{ matrix.variant.suffix }}- + KEEP: ccache-linux-${{ matrix.variant.suffix }}-gcc${{ steps.ccache-key.outputs.gcc }}-${{ github.sha }} + run: | + gh cache list --repo "$GITHUB_REPOSITORY" --ref "$GITHUB_REF" --key "$PREFIX" --limit 100 --json id,key \ + --jq ".[] | select(.key != env.KEEP) | .id" | + while read -r id; do + gh cache delete "$id" --repo "$GITHUB_REPOSITORY" || echo "::warning::cache $id not deleted" + done + # the build copies the shared libraries next to the game (CMake_modules/bundle_runtime_libs.cmake) and the # game looks for them there first ($ORIGIN): each one it loads from outside build/bin has to be one of the system - name: Check the bundled libraries From b47de97e550c2b3a0cf7546c3b488cef3cc4a0f4 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Thu, 26 Nov 2026 05:25:32 +0100 Subject: [PATCH 06/30] ci: keep the newest cache when two runs finish together; write permission only in the cleanup job --- .github/workflows/build_bin.yml | 66 ++++++++++++++++++++++++--------- 1 file changed, 48 insertions(+), 18 deletions(-) diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index b44a71590..dc612e0fd 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -205,10 +205,11 @@ jobs: linux: name: Linux x64 / GCC / ${{ matrix.variant.name }} runs-on: ubuntu-24.04 - # actions: write only to delete the older compiler caches after a save (the step after "Save the compiler cache") - permissions: - contents: read - actions: write + # the key of a compiler cache saved here, one output per variant (a matrix job's outputs are shared by its legs): + # the job linux-ccache-cleanup deletes the older ones, so this job needs no write access + outputs: + ccache-key-avx2: ${{ steps.ccache-saved.outputs.avx2 }} + ccache-key-noavx2: ${{ steps.ccache-saved.outputs.noavx2 }} # see the notes above the windows job: two variants, each with a concurrency group of its own concurrency: group: ${{ github.workflow }}-linux-${{ matrix.variant.suffix }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} @@ -219,7 +220,8 @@ jobs: matrix: # a pull request from a branch of this repository builds the AVX2 variant only; the variant without AVX2 # (the same sources, one compiler switch) is built by the push of that branch, by the pushes to staging - # and master and by a manual run. a pull request from a fork has no push run here, so it builds both + # and master and by a manual run. a pull request from a fork has no push run here, so it builds both. + # so the "No AVX2" jobs of a pull request of this repository never run: don't make them a required check variant: ${{ fromJSON(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"}]' || '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"},{"name":"No AVX2","suffix":"noavx2","cmake_flags":"-DENABLE_AVX2=OFF"}]') }} steps: @@ -374,21 +376,13 @@ jobs: path: ${{ runner.temp }}/ccache key: ccache-linux-${{ matrix.variant.suffix }}-gcc${{ steps.ccache-key.outputs.gcc }}-${{ github.sha }} - # a cache can't be written over, so every save above is a new key of up to 0.5 GB. the older ones of this branch - # and variant (of any GCC) go right after it, or they'd fill the 10 GB of the repository and push out the small - # caches (audio-dlls-*, apt-*). a failed delete only leaves the old cache to the eviction - - name: Delete the older compiler caches + # for the job linux-ccache-cleanup, which deletes the older caches of this branch and variant + - name: Pass on the saved compiler cache key + id: ccache-saved if: ${{ !cancelled() && steps.ccache-save.outcome == 'success' }} env: - GH_TOKEN: ${{ github.token }} - PREFIX: ccache-linux-${{ matrix.variant.suffix }}- - KEEP: ccache-linux-${{ matrix.variant.suffix }}-gcc${{ steps.ccache-key.outputs.gcc }}-${{ github.sha }} - run: | - gh cache list --repo "$GITHUB_REPOSITORY" --ref "$GITHUB_REF" --key "$PREFIX" --limit 100 --json id,key \ - --jq ".[] | select(.key != env.KEEP) | .id" | - while read -r id; do - gh cache delete "$id" --repo "$GITHUB_REPOSITORY" || echo "::warning::cache $id not deleted" - done + KEY: ccache-linux-${{ matrix.variant.suffix }}-gcc${{ steps.ccache-key.outputs.gcc }}-${{ github.sha }} + run: echo "${{ matrix.variant.suffix }}=$KEY" >> "$GITHUB_OUTPUT" # the build copies the shared libraries next to the game (CMake_modules/bundle_runtime_libs.cmake) and the # game looks for them there first ($ORIGIN): each one it loads from outside build/bin has to be one of the system @@ -453,6 +447,42 @@ jobs: retention-days: 14 + # a cache can't be written over, so every save of the linux job is a new key of up to 0.5 GB. the older ones of the + # branch and variant (of any GCC) go right after it, or they'd fill the 10 GB of the repository and push out the + # small caches (audio-dlls-*, apt-*). only the caches created before the one saved go: when two runs of a branch end + # together, the one which saved later keeps its cache. a failed delete only leaves the old cache to the eviction + linux-ccache-cleanup: + name: Linux / delete the older compiler caches + needs: linux + if: ${{ !cancelled() && (needs.linux.outputs.ccache-key-avx2 != '' || needs.linux.outputs.ccache-key-noavx2 != '') }} + runs-on: ubuntu-24.04 + permissions: + actions: write + + steps: + - name: Delete the older compiler caches + env: + GH_TOKEN: ${{ github.token }} + SAVED: ${{ needs.linux.outputs.ccache-key-avx2 }} ${{ needs.linux.outputs.ccache-key-noavx2 }} + run: | + # the ids of the caches created before the one saved (env.KEEP); none when it isn't listed. the times are + # compared as numbers, as their fractions of a second can have any number of digits + older=' + def t: capture("^(?[^.Z]+)(?[.][0-9]+)?Z$") | ((.s + "Z") | fromdateiso8601) + (("0" + (.f // "")) | tonumber); + (map(select(.key == env.KEEP)) | first | .createdAt) as $saved + | if $saved == null then empty else ($saved | t) as $at | .[] | select((.createdAt | t) < $at) | .id end' + for KEEP in $SAVED; do + export KEEP + # the key without its GCC version and commit: ccache-linux-- + prefix="${KEEP%%-gcc*}-" + gh cache list --repo "$GITHUB_REPOSITORY" --ref "$GITHUB_REF" --key "$prefix" --limit 100 \ + --json id,key,createdAt --jq "$older" | + while read -r id; do + gh cache delete "$id" --repo "$GITHUB_REPOSITORY" || echo "::warning::cache $id not deleted" + done + done + + # ============================================================ # Public download: release assets need no GitHub account # ============================================================ From 22ebc41d7080f9a0b9214ee5a5a0da6ff23aae0b Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 09:37:01 +0100 Subject: [PATCH 07/30] refactor(physics): the parts of the main circuit keep their state to themselves The line breaker, the line contactors, the protective relays and the converter (physics/components/maincircuit.h) become classes: what the .fiz defines is in their public `config`, their state is private, read through queries (IsClosed(), UndervoltageHolds(), IsRunning()) and changed through operations (Close(), ResetGround(), Switch()). The logic that concerns only them moves in: the initialisation of the main circuit, the ground relay, the pressure switch, the resets of the relays, and the whole step of the converter, which gets what it needs from the vehicle as plain values (ConverterSupply). The vehicle still decides when they act (the interlocks, the controller positions, the voltages); the parts don't take a physics::Vehicle. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- application/driverhints.cpp | 10 +- application/driveruipanels.cpp | 16 +- input/messaging.cpp | 4 +- physics/components/commands.cpp | 17 +- physics/components/controllers.cpp | 80 ++--- physics/components/diesel.cpp | 60 ++-- physics/components/drive.cpp | 38 ++- physics/components/electrics.cpp | 147 +++------ physics/components/fizsections.cpp | 36 +-- physics/components/maincircuit.h | 297 +++++++++++++++--- physics/components/pneumatics.cpp | 4 +- physics/components/traction.cpp | 20 +- physics/vehicle.h | 12 +- simulation/blackboxrecorder.cpp | 4 +- tests/unit/drive.cpp | 10 +- tests/unit/golden.cpp | 2 +- tests/unit/invariants.cpp | 8 +- tests/unit/scenario.cpp | 4 +- tests/unit/test_6dg_power_steps.cpp | 4 +- tests/unit/test_auxiliaries.cpp | 8 +- tests/unit/test_camshaft.cpp | 12 +- tests/unit/test_cntrl.cpp | 12 +- tests/unit/test_collisions.cpp | 4 +- tests/unit/test_commands.cpp | 10 +- tests/unit/test_compressor.cpp | 30 +- tests/unit/test_crew.cpp | 6 +- tests/unit/test_derailment_vehicle.cpp | 2 +- tests/unit/test_engine_shutdown.cpp | 10 +- tests/unit/test_engine_start.cpp | 34 +- tests/unit/test_field_shunting.cpp | 4 +- tests/unit/test_genset.cpp | 46 +-- tests/unit/test_line_contactors.cpp | 32 +- tests/unit/test_line_contactors_interlock.cpp | 60 ++-- tests/unit/test_linebreaker.cpp | 22 +- tests/unit/test_mains_before_pantographs.cpp | 86 ++--- tests/unit/test_oil_pump.cpp | 4 +- tests/unit/test_pressure_switch.cpp | 76 ++--- tests/unit/test_smoke.cpp | 6 +- tests/unit/test_speed_control.cpp | 10 +- tests/unit/test_traction.cpp | 8 +- vehicle/ai/consist.cpp | 14 +- vehicle/ai/controls.cpp | 18 +- vehicle/ai/engine.cpp | 6 +- vehicle/ai/situation.cpp | 4 +- vehicle/cab/auxiliarycommands.cpp | 16 +- vehicle/cab/powercommands.cpp | 14 +- vehicle/cab/setup.cpp | 8 +- vehicle/cab/train.cpp | 12 +- vehicle/cab/update.cpp | 62 ++-- vehicle/dynamic/sounds.cpp | 12 +- vehicle/dynamic/update.cpp | 12 +- vehicle/enginestart.cpp | 2 +- widgets/vehicleparams.cpp | 8 +- 53 files changed, 789 insertions(+), 654 deletions(-) diff --git a/application/driverhints.cpp b/application/driverhints.cpp index d59431dc6..0f49b1933 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -181,7 +181,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) Action, [this](float const /*Parameter*/) { auto const &device { occupied->OilPump }; - return device.start_type != start_t::manual || device.is_enabled == true || device.is_active == true || occupied->lineBreaker.closed; } ); + return device.start_type != start_t::manual || device.is_enabled == true || device.is_active == true || occupied->lineBreaker.IsClosed(); } ); break; } case driver_hint::oilpumpoff: { @@ -334,7 +334,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) []( TDynamicObject * Vehicle ) { auto *vehicle { Vehicle->physics }; if( vehicle->LineContactorsHeldByLocalConverterSwitch() ) { - vehicle->converter.allowLocal = true; } } ); + vehicle->converter.SetLocalSwitch(true); } } ); } remove_hint( driver_hint::converteroff ); hint( @@ -362,7 +362,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->converter.overloadRelayStart != start_t::manual || occupied->converter.overloaded == false; } ); + return occupied->converter.config.overloadRelayStart != start_t::manual || occupied->converter.IsOverloaded() == false; } ); break; } case driver_hint::maincircuitgroundreset: { @@ -372,7 +372,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->protection.groundStart != start_t::manual || occupied->protection.ground == true; } ); + return occupied->protection.config.groundStart != start_t::manual || occupied->protection.GroundHolds() == true; } ); break; } case driver_hint::tractionnmotoroverloadreset: { @@ -406,7 +406,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) Action, [this](float const /*Parameter*/) { // TBD, TODO: replace with consist-wide flag set true if any line breaker is closed? - return mvControlling->lineBreaker.closed == false; } ); + return mvControlling->lineBreaker.IsClosed() == false; } ); break; } // compressor diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 3e3ce61f0..493f65ce5 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -842,21 +842,21 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.OilPump.is_active ? 'O' : physics.OilPump.is_enabled ? 'o' : '.', - physics.lineBreaker.closed ? 'M' : '.', + physics.lineBreaker.IsClosed() ? 'M' : '.', physics.FuseFlag ? '!' : '.', - physics.converter.running ? 'X' : - false == physics.converter.allowLocal ? '-' : - physics.converter.allow ? 'x' : + physics.converter.IsRunning() ? 'X' : + false == physics.converter.LocalSwitchOn() ? '-' : + physics.converter.IsAllowed() ? 'x' : '.', - physics.converter.overloaded ? '!' : '.', + physics.converter.IsOverloaded() ? '!' : '.', physics.air.compressor.running ? 'C' : false == physics.air.compressor.allowLocal ? '-' : physics.air.compressor.allow || (physics.air.compressor.start == start_t::automatic && physics.air.compressor.speed > 0.0) ? 'c' : '.', physics.air.compressor.governorLock ? '!' : '.', - physics.lineContactors.forcedOpen ? '-' : - physics.protection.pressureSwitch ? '!' : - physics.lineContactors.closed ? '+' : + physics.lineContactors.IsForcedOpen() ? '-' : + physics.protection.PressureSwitchTripped() ? '!' : + physics.lineContactors.IsClosed() ? '+' : '.', physics.trainHeating.on ? 'H' : physics.trainHeating.allow ? 'h' : diff --git a/input/messaging.cpp b/input/messaging.cpp index 283bd15e8..64a0a74f8 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -295,9 +295,9 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) r.iPar[20] = Vehicle->physics->ScndCtrlActualPos; // Pozycja bocznikowania r.iPar[21] = Vehicle->physics->ScndCtrlActualPos; // Pozycja bocznikowania r.iPar[22] = Vehicle->physics->ResistorsFlag * 1 - + Vehicle->physics->converter.running * 2 + + Vehicle->physics->converter.IsRunning() * 2 + Vehicle->physics->air.compressor.running * 4 - + Vehicle->physics->lineBreaker.closed * 8 + + Vehicle->physics->lineBreaker.IsClosed() * 8 #ifdef EU07_USEOLDDOORCODE + Vehicle->physics->DoorLeftOpened * 16 + Vehicle->physics->DoorRightOpened * 32 diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index a5d6f6a2d..875431621 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -144,11 +144,11 @@ bool physics::Vehicle::RunControllerCommand(VehicleCommand const Command, double MainCtrlPos = position; if (DelayCtrlFlag) { - if (lineContactors.lastSwitchTime >= InitialCtrlDelay && MainCtrlPos == 1) - lineContactors.lastSwitchTime = 0; + if (lineContactors.TimeSinceSwitch() >= InitialCtrlDelay && MainCtrlPos == 1) + lineContactors.RestartSwitchTimer(); } - else if (lineContactors.lastSwitchTime > CtrlDelay) - lineContactors.lastSwitchTime = 0; + else if (lineContactors.TimeSinceSwitch() > CtrlDelay) + lineContactors.RestartSwitchTimer(); } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } @@ -157,8 +157,8 @@ bool physics::Vehicle::RunControllerCommand(VehicleCommand const Command, double if (ScndCtrlPosNo >= floor(CValue1)) { ScndCtrlPos = static_cast(floor(CValue1)); - if (lineContactors.lastSwitchTime > CtrlDelay) - lineContactors.lastSwitchTime = 0; + if (lineContactors.TimeSinceSwitch() > CtrlDelay) + lineContactors.RestartSwitchTimer(); } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } @@ -364,10 +364,7 @@ bool physics::Vehicle::RunAuxiliariesCommand(VehicleCommand const Command, doubl } else if (Command == VehicleCommand::converterSwitch) /*NBMX*/ { - if (converter.start == start_t::manual) - { - converter.allow = CValue1 > 0.0; - } + converter.Switch(CValue1 > 0.0); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else if (Command == VehicleCommand::batterySwitch) /*NBMX*/ diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index d88cdc6c8..4016f25a9 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -97,11 +97,11 @@ bool physics::Vehicle::IncMainCtrl(int CtrlSpeed) { if (DelayCtrlFlag) { - if (lineContactors.lastSwitchTime >= InitialCtrlDelay && MainCtrlPos == 1) - lineContactors.lastSwitchTime = 0; + if (lineContactors.TimeSinceSwitch() >= InitialCtrlDelay && MainCtrlPos == 1) + lineContactors.RestartSwitchTimer(); } - else if (lineContactors.lastSwitchTime > CtrlDelay) - lineContactors.lastSwitchTime = 0; + else if (lineContactors.TimeSinceSwitch() > CtrlDelay) + lineContactors.RestartSwitchTimer(); } return OK; } @@ -226,11 +226,11 @@ bool physics::Vehicle::DecMainCtrl(int CtrlSpeed) { if (DelayCtrlFlag) { - if (lineContactors.lastSwitchTime >= InitialCtrlDelay) - lineContactors.lastSwitchTime = 0; + if (lineContactors.TimeSinceSwitch() >= InitialCtrlDelay) + lineContactors.RestartSwitchTimer(); } - else if (lineContactors.lastSwitchTime > CtrlDownDelay) - lineContactors.lastSwitchTime = 0; + else if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) + lineContactors.RestartSwitchTimer(); } return OK; } @@ -363,7 +363,7 @@ bool physics::Vehicle::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() || fieldshunting::diesel_electric(AutoRelayType, FieldShuntSwitch, AutoRelayFlag) != fieldshunting::control::manual || ShuntMode || false == lineBreaker.closed)) + (IsMainCtrlNoPowerPos() || fieldshunting::diesel_electric(AutoRelayType, FieldShuntSwitch, AutoRelayFlag) != fieldshunting::control::manual || ShuntMode || false == lineBreaker.IsClosed())) { OK = false; } @@ -392,8 +392,8 @@ bool physics::Vehicle::IncScndCtrl(int CtrlSpeed) OK = false; // if OK then LastRelayTime:=0; // hunter-101012: poprawka - if (OK && lineContactors.lastSwitchTime > CtrlDelay) - lineContactors.lastSwitchTime = 0; + if (OK && lineContactors.TimeSinceSwitch() > CtrlDelay) + lineContactors.RestartSwitchTimer(); if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1 && MainCtrlPos > 0) { @@ -454,8 +454,8 @@ bool physics::Vehicle::DecScndCtrl(int CtrlSpeed) OK = false; // if OK then LastRelayTime:=0; // hunter-101012: poprawka - if (OK && lineContactors.lastSwitchTime > CtrlDownDelay) - lineContactors.lastSwitchTime = 0; + if (OK && lineContactors.TimeSinceSwitch() > CtrlDownDelay) + lineContactors.RestartSwitchTimer(); if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1) { @@ -549,7 +549,7 @@ bool physics::Vehicle::AutoRelayCheck(void) // yBARC - rozlaczenie stycznikow liniowych if (motorconnectorsoff || (HasCamshaft ? IsMainCtrlActualNoPowerPos() : IsMainCtrlNoPowerPos())) { - lineContactors.closed = false; + lineContactors.Open(); if (false == brakes.electrodynamic.on) { Im = 0; @@ -569,7 +569,7 @@ bool physics::Vehicle::AutoRelayCheck(void) // przejście dalej przez danie nastawnika na dalszą pozycję - tak to do // tej pory działało i na tym się opiera fizyka ET22-2k { - if (lineContactors.closed) + if (lineContactors.IsClosed()) { if (RList[MainCtrlActualPos].R == 0 && (ScndCtrlActualPos > 0 || ScndCtrlPos > 0) && (!CoupledCtrl || RList[MainCtrlActualPos].Relay == MainCtrlPos)) { // zmieniaj scndctrlactualpos @@ -585,7 +585,7 @@ bool physics::Vehicle::AutoRelayCheck(void) OK = AutoRelayLineContactorsStep(motorconnectorsoff); } if (OK) - lineContactors.lastSwitchTime = 0; + lineContactors.RestartSwitchTimer(); return OK; } @@ -598,7 +598,7 @@ bool physics::Vehicle::AutoRelayShuntStep(bool const ARFASI2) // scnd bez samoczynnego rozruchu if (ScndCtrlActualPos < ScndCtrlPos) { - if (lineContactors.lastSwitchTime > CtrlDelay && ARFASI2) + if (lineContactors.TimeSinceSwitch() > CtrlDelay && ARFASI2) { ++ScndCtrlActualPos; SetFlag(SoundFlag, sound::shuntfield); @@ -607,7 +607,7 @@ bool physics::Vehicle::AutoRelayShuntStep(bool const ARFASI2) } else if (ScndCtrlActualPos > ScndCtrlPos) { - if (lineContactors.lastSwitchTime > CtrlDownDelay && TrainType != train_type::emu) + if (lineContactors.TimeSinceSwitch() > CtrlDownDelay && TrainType != train_type::emu) { --ScndCtrlActualPos; SetFlag(SoundFlag, sound::shuntfield); @@ -640,7 +640,7 @@ bool physics::Vehicle::AutoRelayMainStep(bool const ARFASI) } else if (RList[MainCtrlActualPos].R > 0 && ScndCtrlActualPos > 0) { - if (lineContactors.lastSwitchTime > CtrlDownDelay) + if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) { --ScndCtrlActualPos; // boczniki nie dzialaja na poz. oporowych SetFlag(SoundFlag, sound::shuntfield); @@ -681,7 +681,7 @@ bool physics::Vehicle::AutoRelayMainUp(bool const ARFASI) OK = true; } } - else if (lineContactors.lastSwitchTime > CtrlDelay && ARFASI) + else if (lineContactors.TimeSinceSwitch() > CtrlDelay && ARFASI) { OK = AutoRelayMainNotchUp(); } @@ -704,7 +704,7 @@ bool physics::Vehicle::AutoRelayMainNotchUp() DelayCtrlFlag = true; // tryb przejscia OK = true; } - else if (lineContactors.lastSwitchTime > 4 * CtrlDelay) // przejscie + else if (lineContactors.TimeSinceSwitch() > 4 * CtrlDelay) // przejscie { DelayCtrlFlag = false; @@ -753,7 +753,7 @@ bool physics::Vehicle::AutoRelayMainDown() SetFlag(SoundFlag, sound::parallel); } } - else if (lineContactors.lastSwitchTime > CtrlDownDelay) + else if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) { if (TrainType != train_type::emu) // tutaj powinien być tryb sterowania wałem { @@ -779,9 +779,9 @@ bool physics::Vehicle::AutoRelayLineContactorsStep(bool const motorconnectorsoff { DelayCtrlFlag = true; - if (lineContactors.lastSwitchTime >= InitialCtrlDelay) + if (lineContactors.TimeSinceSwitch() >= InitialCtrlDelay) { - lineContactors.closed = true; + lineContactors.Close(); MainCtrlActualPos = 1; DelayCtrlFlag = false; SetFlag(SoundFlag, sound::relay | sound::loud); @@ -793,7 +793,7 @@ bool physics::Vehicle::AutoRelayLineContactorsStep(bool const motorconnectorsoff DelayCtrlFlag = false; } - if (false == lineContactors.closed && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) + if (false == lineContactors.IsClosed() && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) { OK |= CamshaftRunDown(); } @@ -813,7 +813,7 @@ bool physics::Vehicle::CamshaftRunDown() { OK = CamshaftRunDownEMU(); } - else if (lineContactors.lastSwitchTime > CtrlDownDelay) // wal kulakowy dwukierunkowy + else if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) // wal kulakowy dwukierunkowy { if (ScndCtrlActualPos > 0) { @@ -830,7 +830,7 @@ bool physics::Vehicle::CamshaftRunDown() else if (HasCamshaft) { // wal kulakowy dwukierunkowy - if (lineContactors.lastSwitchTime > CtrlDownDelay) + if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) { if (MainCtrlActualPos > 0) { @@ -863,7 +863,7 @@ bool physics::Vehicle::CamshaftRunDownEMU() else { - if (lineContactors.lastSwitchTime > CtrlDownDelay) + if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) { if (MainCtrlActualPos < RlistSize) @@ -894,29 +894,29 @@ bool physics::Vehicle::MotorConnectorsCheck() // hunter-111211: wylacznik cisnieniowy // (on some vehicles it watches the brake pipe alone) - protection.pressureSwitch = protection.hasPressureSwitch && ((protection.pressureSwitchWatchesCylinders && brakes.cylinderPressure > 2.0) || brakePipe.pressure < 3.6); + protection.UpdatePressureSwitch(brakes.cylinderPressure, brakePipe.pressure); - if (true == protection.pressureSwitch) + if (true == protection.PressureSwitchTripped()) { return false; } // a line breaker closed ahead of the pantographs holds without voltage; what cuts the motors off there is its // undervoltage relay, which elsewhere opens the line breaker - auto const undervoltage{lineBreaker.pantographsRequireIt && false == protection.noVoltage}; + auto const undervoltage{lineBreaker.config.pantographsRequireIt && false == protection.UndervoltageHolds()}; - auto const connectorsoff{false == lineBreaker.closed || undervoltage || true == FuseFlag || true == lineContactors.forcedOpen || DirActive == 0}; + auto const connectorsoff{false == lineBreaker.IsClosed() || undervoltage || true == FuseFlag || true == lineContactors.IsForcedOpen() || DirActive == 0}; return false == connectorsoff && LineContactorsInterlockReleased(); } bool physics::Vehicle::LineContactorsInterlockReleased() const { - switch (lineContactors.interlock) + switch (lineContactors.config.interlock) { case line_contactors_interlock::converter: // the converter of this very vehicle, not the 110 V of the trainset: a section with its fans off doesn't start - return converter.running; + return converter.IsRunning(); case line_contactors_interlock::motor_blowers: return std::ranges::all_of(MotorBlowers, [this](auto const &Blower) { if (Blower.min_start_velocity < 0) @@ -1092,7 +1092,7 @@ void physics::Vehicle::EIMICFromFourPositions(double dt) // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() eimic = -1.0; } - else if (MainCtrlActualPos != MainCtrlPos || lineContactors.lastSwitchTime > InitialCtrlDelay) + else if (MainCtrlActualPos != MainCtrlPos || lineContactors.TimeSinceSwitch() > InitialCtrlDelay) { double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; // the positions below are those of the controller without the emergency brake position @@ -1120,10 +1120,10 @@ void physics::Vehicle::EIMICFromFourPositions(double dt) } } if (MainCtrlActualPos == MainCtrlPos) - lineContactors.lastSwitchTime += dt; + lineContactors.AdvanceSwitchTimer(dt); else { - lineContactors.lastSwitchTime = 0; + lineContactors.RestartSwitchTimer(); MainCtrlActualPos = MainCtrlPos; } } @@ -1136,7 +1136,7 @@ void physics::Vehicle::EIMICFromUniversalController(double dt, double const brak UniversalControllerTrainBrake(); } - if (MainCtrlActualPos != MainCtrlPos || lineContactors.lastSwitchTime > InitialCtrlDelay) + if (MainCtrlActualPos != MainCtrlPos || lineContactors.TimeSinceSwitch() > InitialCtrlDelay) { auto const &position{UniCtrlList[MainCtrlPos]}; double ramped{eimic}; @@ -1148,10 +1148,10 @@ void physics::Vehicle::EIMICFromUniversalController(double dt, double const brak eimic = UniCtrlValStep > 0.0 ? stepped_uc_value(eimic, ramped, position, UniCtrlValStep, MainCtrlActualPos != MainCtrlPos, eimic_step_progress) : ramped; } if (MainCtrlActualPos == MainCtrlPos) - lineContactors.lastSwitchTime += dt; + lineContactors.AdvanceSwitchTimer(dt); else { - lineContactors.lastSwitchTime = 0; + lineContactors.RestartSwitchTimer(); MainCtrlActualPos = MainCtrlPos; } if (brakes.distributor->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake diff --git a/physics/components/diesel.cpp b/physics/components/diesel.cpp index d7e7ecc85..decd11eb5 100644 --- a/physics/components/diesel.cpp +++ b/physics/components/diesel.cpp @@ -76,8 +76,8 @@ void physics::Vehicle::FuelPumpCheck(double const /*Timestep*/) FuelPump.is_active = true == (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) && false == FuelPump.is_disabled && (FuelPump.is_active || (FuelPump.start_type == manual ? FuelPump.is_enabled : - FuelPump.start_type == automatic ? diesel.startupRequested || lineBreaker.closed : - FuelPump.start_type == manualwithautofallback ? FuelPump.is_enabled || diesel.startupRequested || lineBreaker.closed : + FuelPump.start_type == automatic ? diesel.startupRequested || lineBreaker.IsClosed() : + FuelPump.start_type == manualwithautofallback ? FuelPump.is_enabled || diesel.startupRequested || lineBreaker.IsClosed() : false)); // shouldn't ever get this far but, eh } @@ -85,7 +85,7 @@ void physics::Vehicle::FuelPumpCheck(double const /*Timestep*/) void physics::Vehicle::OilPumpCheck(double const Timestep) { - OilPump.is_active = true == (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) && false == lineBreaker.closed && false == OilPump.is_disabled && + OilPump.is_active = true == (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) && false == lineBreaker.IsClosed() && false == OilPump.is_disabled && (OilPump.is_active || (OilPump.start_type == start_t::manual ? OilPump.is_enabled : OilPump.start_type == start_t::automatic ? diesel.startupRequested : OilPump.start_type == start_t::manualwithautofallback ? OilPump.is_enabled || diesel.startupRequested : @@ -339,7 +339,7 @@ double physics::Vehicle::DieselElectricTargetRevolutions() 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[protection.pressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; + tmp = DElist[protection.PressureSwitchTripped() ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; if (true == trainHeating.allow && trainHeating.power > 0 && trainHeating.engineRpm > 0) { @@ -399,7 +399,7 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) PosRatio = currentgenpower / DElist[MainCtrlPosNo].GenPower; // stosunek mocy teraz do mocy max // NOTE: Mains in this context is working diesel engine - if (true == lineContactors.closed) + if (true == lineContactors.IsClosed()) Ft = DieselElectricForce(tmpV, power, PosRatio, tmp); else Ft = 0; // jak nastawnik na zero, to sila tez zero @@ -433,7 +433,7 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) // przekazniki bocznikowania, kazdy inny dla kazdej pozycji if (auto const fieldshuntingcontrol{fieldshunting::diesel_electric(AutoRelayType, FieldShuntSwitch, AutoRelayFlag)}; - false == lineContactors.closed || ShuntMode || fieldshuntingcontrol == fieldshunting::control::off) + false == lineContactors.IsClosed() || ShuntMode || fieldshuntingcontrol == fieldshunting::control::off) { ScndCtrlPos = 0; } @@ -448,7 +448,7 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) // tmp, the power the generator gives void physics::Vehicle::DieselElectricShuntForce(double const tmpV, double &tmp) { - if (true == lineContactors.closed) + if (true == lineContactors.IsClosed()) { 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 @@ -472,7 +472,7 @@ double physics::Vehicle::DieselElectricDigitalForce(double const tmpV, double &t 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 == lineContactors.closed) + if (true == lineContactors.IsClosed()) Ft = DieselElectricForce(tmpV, tempPmax, eimic_positive, tempPmax); else Ft = 0; // jak nastawnik na zero, to sila tez zero @@ -539,7 +539,7 @@ void physics::Vehicle::DieselElectricGenerator(double const tmp, double const te if (EngineVoltage > tempUmax || Im == 0) { // gdy wychodzi za duze napiecie albo przy biegu jalowym (jest cos takiego?) - EngineVoltage = tempUmax * (converter.running ? 1 : 0); + EngineVoltage = tempUmax * (converter.IsRunning() ? 1 : 0); } EnginePower = EngineVoltage * Im / 1000.0; @@ -609,7 +609,7 @@ void physics::Vehicle::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 (lineBreaker.closed && DirActive != 0 && false == FuseFlag && false == SlippingWheels && nopower) + if (lineBreaker.IsClosed() && DirActive != 0 && false == FuseFlag && false == SlippingWheels && nopower) { brake.level += std::clamp(dieselelectric_dynamic_brake_demand() - brake.level, -brake.rate * dt, brake.rate * dt); } @@ -705,12 +705,12 @@ bool physics::Vehicle::dizel_AutoGearCheck(void) auto const VelDown{(motor_param(ScndCtrlActualPos).fi0 != 0.0 && eimic_real <= 0.0 ? motor_param(ScndCtrlActualPos).fi0 : motor_param(ScndCtrlActualPos).fi)}; - if (motor_param(ScndCtrlActualPos).AutoSwitch && lineBreaker.closed) + if (motor_param(ScndCtrlActualPos).AutoSwitch && lineBreaker.IsClosed()) { OK = dizel_GearShiftCheck(VelUp, VelDown); } - if (lineBreaker.closed) + if (lineBreaker.IsClosed()) { dizel_ClutchCheck(); } @@ -892,7 +892,7 @@ bool physics::Vehicle::dizel_Update(double dt) OilPumpCheck(dt); FuelPumpCheck(dt); // the engine being started fires once the starter has turned it a while; one stopped meanwhile starts over - diesel.firingCountdown = (lineBreaker.closed ? std::max(0.0, diesel.firingCountdown - dt) : 0.0); + diesel.firingCountdown = (lineBreaker.IsClosed() ? std::max(0.0, diesel.firingCountdown - dt) : 0.0); if (true == diesel.startupRequested && true == dizel_StartupCheck()) { @@ -907,7 +907,7 @@ bool physics::Vehicle::dizel_Update(double dt) // TODO: split engine and main circuit state indicator in two separate flags LastSwitchingTime = 0; Timer::subsystem.switching.note(Timer::switching_counter::diesel, this, &TypeName, &Name); - lineBreaker.closed = true; + lineBreaker.Close(); diesel.spinningUp = true; diesel.firingCountdown = diesel.smokeDelay; enrot = std::max(enrot, @@ -915,9 +915,9 @@ bool physics::Vehicle::dizel_Update(double dt) EngineType == TEngineType::DieselEngine ? diesel.minRevolutions : DElist[0].RPM / 60.0)); } - diesel.spinningUp = diesel.spinningUp && lineBreaker.closed && enrot < 0.95 * (EngineType == TEngineType::DieselEngine ? diesel.minRevolutions : DElist[0].RPM / 60.0); + diesel.spinningUp = diesel.spinningUp && lineBreaker.IsClosed() && enrot < 0.95 * (EngineType == TEngineType::DieselEngine ? diesel.minRevolutions : DElist[0].RPM / 60.0); - if (true == lineBreaker.closed && false == FuelPump.is_active) + if (true == lineBreaker.IsClosed() && false == FuelPump.is_active) { // knock out the engine if the fuel pump isn't feeding it // TBD, TODO: grace period before the engine is starved for fuel and knocked out @@ -948,7 +948,7 @@ double physics::Vehicle::dizel_fillcheck(int mcp, double dt) { auto realfill{0.0}; - if (true == lineBreaker.closed && MainCtrlPosNo > 0 && true == FuelPump.is_active) + if (true == lineBreaker.IsClosed() && MainCtrlPosNo > 0 && true == FuelPump.is_active) { if (true == diesel.ignitionRequested && LastSwitchingTime >= 0.9 * InitialCtrlDelay) @@ -1184,7 +1184,7 @@ double physics::Vehicle::dizel_Momentum(double Fill, double n, double dt) // an engine stalling stops those started together with it, once. one already stopped, from its own switch or // another vehicle's, or not started at all, has nothing to stop: it stays quiet, rather than stop every frame // the engines started on their own or from the separate switches (eu07/maszyna#80) - if (true == lineBreaker.closed) + if (true == lineBreaker.IsClosed()) { MainSwitch(false, MainSwitchRange()); } @@ -1203,22 +1203,22 @@ void physics::Vehicle::hydro_TCFillCheck(double dt) { // napelnianie przetwornika bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; - if (IsPower && lineBreaker.closed && enrot > diesel.minRevolutions * 0.9) + if (IsPower && lineBreaker.IsClosed() && enrot > diesel.minRevolutions * 0.9) torqueConverter.fill += torqueConverter.fillRateIncrease * dt; // oproznianie przetwornika - if ((!IsPower && Vel < diesel.converterReleaseVelocity) || !lineBreaker.closed || enrot < diesel.minRevolutions * 0.8) + if ((!IsPower && Vel < diesel.converterReleaseVelocity) || !lineBreaker.IsClosed() || enrot < diesel.minRevolutions * 0.8) torqueConverter.fill -= torqueConverter.fillRateDecrease * dt; // obcinanie zakresu torqueConverter.fill = std::clamp(torqueConverter.fill, 0.0, 1.0); // blokowanie sprzegla blokującego - if (Vel > torqueConverter.lockupSpeed && lineBreaker.closed && enrot > 0.9 * diesel.minRevolutions && IsPower) + if (Vel > torqueConverter.lockupSpeed && lineBreaker.IsClosed() && enrot > 0.9 * diesel.minRevolutions && IsPower) { torqueConverter.lockedUp = true; torqueConverter.lockupRate += torqueConverter.fillRateIncrease * dt; } // luzowanie sprzegla blokujacego - if (Vel < (IsPower ? torqueConverter.lockupSpeed : torqueConverter.unlockSpeed) || !lineBreaker.closed || enrot < 0.8 * diesel.minRevolutions) + if (Vel < (IsPower ? torqueConverter.lockupSpeed : torqueConverter.unlockSpeed) || !lineBreaker.IsClosed() || enrot < 0.8 * diesel.minRevolutions) { torqueConverter.lockedUp = false; torqueConverter.lockupRate -= torqueConverter.fillRateDecrease * dt; @@ -1266,7 +1266,7 @@ void physics::Vehicle::hydro_TCTorque() double physics::Vehicle::dizel_MomentumRetarder(double n, double dt) { - double RetarderRequest = lineBreaker.closed ? std::max(0.0, -eimic_real) : 0; + double RetarderRequest = lineBreaker.IsClosed() ? std::max(0.0, -eimic_real) : 0; if (retarder.withIndividual) RetarderRequest = LocalBrakeRatio(); if (Vel < retarder.minVelocity) @@ -1344,8 +1344,8 @@ void physics::Vehicle::dizel_Heat(double const dt) diesel.heat.Te = Global.AirTemperature; - auto const engineon{(lineBreaker.closed ? 1 : 0)}; - auto const engineoff{(lineBreaker.closed ? 0 : 1)}; + auto const engineon{(lineBreaker.IsClosed() ? 1 : 0)}; + auto const engineoff{(lineBreaker.IsClosed() ? 0 : 1)}; auto const rpm{enrot * 60}; // TODO: calculate this once and cache for further use, instead of doing it repeatedly all over the place auto const revolutionsfactor{EngineRPMRatio()}; @@ -1355,11 +1355,11 @@ void physics::Vehicle::dizel_Heat(double const dt) auto const gw2 = engineon * std::lerp(gwmin2, gwmax2, revolutionsfactor) + waterpump * 1000 + engineoff * 200; auto const gwO = std::lerp(gwmin, gwmax, revolutionsfactor); - diesel.heat.water.is_cold = diesel.heat.water.config.temp_min > 0 && diesel.heat.temperatura1 < diesel.heat.water.config.temp_min - (lineBreaker.closed ? 5 : 0); + diesel.heat.water.is_cold = diesel.heat.water.config.temp_min > 0 && diesel.heat.temperatura1 < diesel.heat.water.config.temp_min - (lineBreaker.IsClosed() ? 5 : 0); diesel.heat.water.is_hot = diesel.heat.water.config.temp_max > 0 && diesel.heat.temperatura1 > diesel.heat.water.config.temp_max - (diesel.heat.water.is_hot ? 8 : 0); - diesel.heat.water_aux.is_cold = diesel.heat.water_aux.config.temp_min > 0 && diesel.heat.temperatura2 < diesel.heat.water_aux.config.temp_min - (lineBreaker.closed ? 5 : 0); + diesel.heat.water_aux.is_cold = diesel.heat.water_aux.config.temp_min > 0 && diesel.heat.temperatura2 < diesel.heat.water_aux.config.temp_min - (lineBreaker.IsClosed() ? 5 : 0); diesel.heat.water_aux.is_hot = diesel.heat.water_aux.config.temp_max > 0 && diesel.heat.temperatura2 > diesel.heat.water_aux.config.temp_max - (diesel.heat.water_aux.is_hot ? 8 : 0); - diesel.heat.oil.is_cold = diesel.heat.oil.config.temp_min > 0 && diesel.heat.To < diesel.heat.oil.config.temp_min - (lineBreaker.closed ? 5 : 0); + diesel.heat.oil.is_cold = diesel.heat.oil.config.temp_min > 0 && diesel.heat.To < diesel.heat.oil.config.temp_min - (lineBreaker.IsClosed() ? 5 : 0); diesel.heat.oil.is_hot = diesel.heat.oil.config.temp_max > 0 && diesel.heat.To > diesel.heat.oil.config.temp_max - (diesel.heat.oil.is_hot ? 8 : 0); // engine overheat check diesel.heat.engine_is_hot = diesel.heat.engine_max_temp > 0 && diesel.heat.Ts > diesel.heat.engine_max_temp - (diesel.heat.engine_is_hot ? 8 : 0); @@ -1400,7 +1400,7 @@ void physics::Vehicle::dizel_Heat(double const dt) { // auxiliary water circuit setup diesel.heat.water_aux.is_warm = true == diesel.heat.cooling || - (true == lineBreaker.closed && lowVoltage.batteryVoltage > 0.75 * lowVoltage.nominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ + (true == lineBreaker.IsClosed() && lowVoltage.batteryVoltage > 0.75 * lowVoltage.nominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ && diesel.heat.water_aux.config.temp_cooling > 0 && diesel.heat.temperatura2 > diesel.heat.water_aux.config.temp_cooling - (diesel.heat.water_aux.is_warm ? 8 : 0)); auto const PTC2{(diesel.heat.water_aux.is_warm /*or PTC2p*/ ? 1 : 0)}; diesel.heat.rpmwz2 = static_cast(PTC2 * (diesel.heat.fan_speed >= 0 ? rpm * diesel.heat.fan_speed : diesel.heat.fan_speed * -1)); @@ -1423,7 +1423,7 @@ void physics::Vehicle::dizel_Heat(double const dt) diesel.heat.water.is_flowing = diesel.heat.water.config.temp_flow < 0 || diesel.heat.temperatura1 > diesel.heat.water.config.temp_flow - (diesel.heat.water.is_flowing ? 5 : 0); auto const obieg{(diesel.heat.water.is_flowing ? 1 : 0)}; diesel.heat.water.is_warm = - true == diesel.heat.cooling || (true == lineBreaker.closed && lowVoltage.batteryVoltage > 0.75 * lowVoltage.nominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ + true == diesel.heat.cooling || (true == lineBreaker.IsClosed() && lowVoltage.batteryVoltage > 0.75 * lowVoltage.nominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ && diesel.heat.water.config.temp_cooling > 0 && diesel.heat.temperatura1 > diesel.heat.water.config.temp_cooling - (diesel.heat.water.is_warm ? 8 : 0)); auto const PTC1{(diesel.heat.water.is_warm /*or PTC1p*/ ? 1 : 0)}; diesel.heat.rpmwz = static_cast(PTC1 * (diesel.heat.fan_speed >= 0 ? rpm * diesel.heat.fan_speed : diesel.heat.fan_speed * -1)); diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index 648c6cac4..309a040ba 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -109,7 +109,7 @@ namespace void updateRadiatorFans(physics::Vehicle &vehicle, double const dt) { auto &heat{vehicle.diesel.heat}; - if (true == vehicle.lineBreaker.closed) + if (true == vehicle.lineBreaker.IsClosed()) { heat.rpmw += static_cast(std::clamp(heat.rpmwz - heat.rpmw, -100.f, 50.f) * dt); heat.rpmw2 += static_cast(std::clamp(heat.rpmwz2 - heat.rpmw2, -100.f, 50.f) * dt); @@ -125,7 +125,7 @@ void updateRadiatorFans(physics::Vehicle &vehicle, double const dt) // else it needs the voltage of the source bool linePowerAvailable(physics::Vehicle const &vehicle) { - return vehicle.lineBreaker.pantographsRequireIt ? vehicle.lowVoltage.power24vAvailable || vehicle.lowVoltage.power110vAvailable : vehicle.EnginePowerSourceVoltage() > 0.5 * vehicle.EnginePowerSource.MaxVoltage; + return vehicle.lineBreaker.config.pantographsRequireIt ? vehicle.lowVoltage.power24vAvailable || vehicle.lowVoltage.power110vAvailable : vehicle.EnginePowerSourceVoltage() > 0.5 * vehicle.EnginePowerSource.MaxVoltage; } // a notch of the master controller of the drives without steps of their own (no engine, Dumb, diesel-electric, @@ -265,13 +265,14 @@ public: // where a start begins, as the line breaker it stands in for wouldn't close on a running position either: at // zero, or at the first position, which is the first resistance step, where the line contactors close on any // start, and where the AI waits for them rather than going back to zero - auto const novoltrelaypicksup{false == vehicle.lineBreaker.pantographsRequireIt || vehicle.protection.noVoltage || vehicle.MainCtrlPowerPos() <= 1}; + auto const novoltrelaypicksup{false == vehicle.lineBreaker.config.pantographsRequireIt || vehicle.protection.UndervoltageHolds() || vehicle.MainCtrlPowerPos() <= 1}; auto const &source{vehicle.EnginePowerSource}; - vehicle.protection.noVoltage = source.SourceType != TPowerSource::CurrentCollector || (voltage >= source.CollectorParameters.MinV && novoltrelaypicksup); - vehicle.protection.overvoltage = source.SourceType != TPowerSource::CurrentCollector || voltage <= source.CollectorParameters.MaxV || false == source.CollectorParameters.OVP; + vehicle.protection.SetVoltageRelays( + source.SourceType != TPowerSource::CurrentCollector || (voltage >= source.CollectorParameters.MinV && novoltrelaypicksup), + source.SourceType != TPowerSource::CurrentCollector || voltage <= source.CollectorParameters.MaxV || false == source.CollectorParameters.OVP); // wywalanie szybkiego z powodu niewłaściwego napięcia // (a line breaker closed ahead of the pantographs holds without voltage) - vehicle.EventFlag |= true == vehicle.lineBreaker.closed && ((false == vehicle.protection.noVoltage && false == vehicle.lineBreaker.pantographsRequireIt) || false == vehicle.protection.overvoltage) && + vehicle.EventFlag |= true == vehicle.lineBreaker.IsClosed() && ((false == vehicle.protection.UndervoltageHolds() && false == vehicle.lineBreaker.config.pantographsRequireIt) || false == vehicle.protection.OvervoltageHolds()) && vehicle.MainSwitch(false, vehicle.TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide } bool UpdateEngine(physics::Vehicle &vehicle, double /*dt*/) const override @@ -281,10 +282,10 @@ public: } void UpdateEngineVoltage(physics::Vehicle &vehicle, double const dt) const override { - vehicle.lineContactors.lastSwitchTime += dt; + vehicle.lineContactors.AdvanceSwitchTimer(dt); // potem ulepszyc! pantogtrafy! // Ra 2014-03: uwzględnienie kierunku jazdy w napięciu na silnikach, a powinien być zdefiniowany nawrotnik - vehicle.EngineVoltage = vehicle.lineBreaker.closed ? vehicle.EnginePowerSourceVoltage() : 0.0; + vehicle.EngineVoltage = vehicle.lineBreaker.IsClosed() ? vehicle.EnginePowerSourceVoltage() : 0.0; if (vehicle.CabActive == 0) { vehicle.EngineVoltage *= vehicle.DirActive; @@ -334,7 +335,7 @@ public: // nie wchodzić w funkcję bez potrzeby // (a line breaker closed ahead of the pantographs holds without voltage) // (the source by the traction selector of a dual-mode vehicle: the pantographs or the genset) - if (vehicle.lineBreaker.closed && ((vehicle.TractionSupplyVoltage() < vehicle.TractionSupplyMinVoltage() && false == vehicle.lineBreaker.pantographsRequireIt) || + if (vehicle.lineBreaker.IsClosed() && ((vehicle.TractionSupplyVoltage() < vehicle.TractionSupplyMinVoltage() && false == vehicle.lineBreaker.config.pantographsRequireIt) || vehicle.TractionSupplyVoltage() > vehicle.EnginePowerSource.CollectorParameters.MaxV + 200)) { vehicle.MainSwitch(false, vehicle.TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide @@ -457,7 +458,7 @@ public: double UpdateEngineRevolutions(physics::Vehicle &vehicle, double const dt, double & /*transmission*/, double & /*moment*/) const override { double target{0.0}; - if (true == vehicle.lineBreaker.closed && true == vehicle.FuelPump.is_active) + if (true == vehicle.lineBreaker.IsClosed() && true == vehicle.FuelPump.is_active) { target = vehicle.DieselElectricTargetRevolutions(); } @@ -494,7 +495,7 @@ public: void UpdateVentilators(physics::Vehicle &vehicle, double const dt) const override { // NOTE: for this type RventRot is the speed of motor blowers; we also update radiator fans while at it - if (true == vehicle.lineBreaker.closed) + if (true == vehicle.lineBreaker.IsClosed()) { // TBD, TODO: currently ignores RVentType, fix this? vehicle.RventRot += std::clamp(vehicle.enrot - vehicle.RventRot, -100.0, 50.0) * dt; @@ -528,9 +529,18 @@ public: void CheckVoltageRelays(physics::Vehicle &vehicle) const override { // TODO: move this to the auto relay check when the electric engine code paths are unified - vehicle.lineContactors.closed |= vehicle.lineBreaker.closed && false == vehicle.lineContactors.closed && vehicle.MainCtrlPowerPos() == 1; - vehicle.lineContactors.closed &= vehicle.MotorConnectorsCheck(); - vehicle.lineContactors.closed &= vehicle.MainCtrlPowerPos() > 0; + if (vehicle.lineBreaker.IsClosed() && false == vehicle.lineContactors.IsClosed() && vehicle.MainCtrlPowerPos() == 1) + { + vehicle.lineContactors.Close(); + } + if (false == vehicle.MotorConnectorsCheck()) + { + vehicle.lineContactors.Open(); + } + if (false == (vehicle.MainCtrlPowerPos() > 0)) + { + vehicle.lineContactors.Open(); + } } bool UpdateEngine(physics::Vehicle &vehicle, double const dt) const override { diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index 178bcab4f..3f426e9d3 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -149,7 +149,7 @@ void physics::Vehicle::UpdateBatteryVoltage(double dt) // 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{lowVoltage.power110vAvailable || (EngineType == DieselElectric && true == lineBreaker.closed) || (EngineType == DieselEngine && true == lineBreaker.closed)}; + auto const converteractive{lowVoltage.power110vAvailable || (EngineType == DieselElectric && true == lineBreaker.IsClosed()) || (EngineType == DieselEngine && true == lineBreaker.IsClosed())}; lowVoltage.batteryVoltage -= BatteryDrain(dt, converteractive); if (lowVoltage.nominalBatteryVoltage / lowVoltage.batteryVoltage > 1.57 && MainSwitch(false) && EngineType != DieselEngine && EngineType != WheelsDriven) @@ -200,7 +200,7 @@ double physics::Vehicle::BatteryDrainCharged(double dt, bool const converteracti sn2 = -(dt * 2.0); // szybki wzrost do 110V else sn2 = 0; - if (lineBreaker.closed) + if (lineBreaker.IsClosed()) sn3 = dt * 0.05; else sn3 = 0; @@ -231,7 +231,7 @@ double physics::Vehicle::BatteryDrainLow(double dt, bool const converteractive) sn2 = -(dt * 50); // szybki wzrost do 110V else sn2 = 0; - if (lineBreaker.closed) + if (lineBreaker.IsClosed()) sn3 = dt * 0.001; else sn3 = 0; @@ -295,34 +295,16 @@ void physics::Vehicle::MainsCheck(double const Deltatime) 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 || (lineBreaker.pantographsRequireIt && (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable))}; + auto const maincircuitpowersupply{std::abs(localvoltage) > 0.1 || GetTrainsetHighVoltage() > 0.1 || (lineBreaker.config.pantographsRequireIt && (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable))}; - if (true == maincircuitpowersupply) + // optional automatic circuit start, once the circuit is initialised + if (lineBreaker.UpdateInitialisation(maincircuitpowersupply, Deltatime) && lineBreaker.config.start != start_t::manual && false == (lineBreaker.IsClosed() || diesel.startupRequested)) { - // all is well - if (lineBreaker.initCountdown >= 0.0) - { - // NOTE: we ensure main circuit readiness meets condition MainsInitTimeCountdown < 0 - // this allows for simpler rejection of cases where MainsInitTime == 0 - lineBreaker.initCountdown -= Deltatime; - } - else - { - // optional automatic circuit start - if (lineBreaker.start != start_t::manual && false == (lineBreaker.closed || diesel.startupRequested)) - { - MainSwitch(true); - } - } - } - else - { - // no power supply - lineBreaker.initCountdown = lineBreaker.initTime; + MainSwitch(true); } // an emergency brake application made under power opens the line breaker, where the vehicle has such an interlock - if (lineBreaker.closed && EmergencyBrakeHoldsMainOff()) + if (lineBreaker.IsClosed() && EmergencyBrakeHoldsMainOff()) { MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); } @@ -335,13 +317,7 @@ void physics::Vehicle::LowVoltagePowerCheck(double const /*Deltatime*/) if (EngineType == TEngineType::ElectricSeriesMotor) { - protection.ground &= lowvoltagepower; - if (protection.groundStart != start_t::manual) - { - // NOTE: we're ignoring intricaties of battery and converter types as they're unlikely to be used - // TODO: generic check method which takes these into account - protection.ground |= lowvoltagepower; - } + protection.UpdateGround(lowvoltagepower); } } @@ -431,7 +407,7 @@ double physics::Vehicle::LocalPowerVoltage(Coupling const kind) case Coupling::power110v: { - if (converter.running) + if (converter.IsRunning()) { localvoltage = lowVoltage.nominalBatteryVoltage; } @@ -590,62 +566,16 @@ void physics::Vehicle::PowerCouplersCurrent(Coupling const kind, bool const loca // sprawdzanie przetwornicy void physics::Vehicle::ConverterCheck(double const Timestep) { - // TODO: move other converter checks here, to have it all in one place for potential device object - if (converter.start != start_t::disabled && converter.overloadRelayOffWithLineBreaker) - { - converter.overloaded |= !lineBreaker.closed && lowVoltage.power24vAvailable; - } - - switch (converter.start) - { - case start_t::disabled: - { - converter.allow = false; - // NOTE: if there's no converter in vehicle we can end the check here - return; - } - case start_t::automatic: - { - converter.allow = lineBreaker.closed; - break; - } - case start_t::direction: - { - converter.allow = DirActive != 0; - } - default: - { - break; - } - } - - if (converter.allow && converter.allowLocal && false == converter.overloaded && - false == pantographAir.pressureLockActive - // HACK: allow carriages to operate converter without (missing) fuse prerequisite - && (Power > 1.0 ? MainCircuitPowered() : GetTrainsetHighVoltage() > 0.0)) - { - // delay timer can be optionally configured, and is set anew whenever converter goes off - if (converter.startDelayTimer <= 0.0) - { - converter.running = true; - } - else - { - converter.startDelayTimer -= Timestep; - } - } - else - { - converter.running = false; - converter.startDelayTimer = static_cast(converter.startDelay); - } - - if (converter.overloadRelayStart == start_t::converter && false == (converter.allow && converter.allowLocal) && false == TestFlag(EngDmgFlag, 4)) - { - // reset converter overload relay if the converter was switched off, unless it's damaged - converter.overloaded = false; - } -}; + ConverterSupply supply; + supply.lineBreakerClosed = lineBreaker.IsClosed(); + supply.lowVoltage24v = lowVoltage.power24vAvailable; + supply.directionActive = DirActive != 0; + supply.pantographPressureLock = pantographAir.pressureLockActive; + // HACK: allow carriages to operate converter without (missing) fuse prerequisite + supply.highVoltage = Power > 1.0 ? MainCircuitPowered() : GetTrainsetHighVoltage() > 0.0; + supply.damaged = TestFlag(EngDmgFlag, 4); + converter.Update(supply, Timestep); +} // heating system status check void physics::Vehicle::HeatingCheck(double const /*Timestep*/) @@ -754,7 +684,7 @@ void physics::Vehicle::PantographsCheck(double const /*Timestep*/) valve.is_active = (valve.spring ? lowvoltagepower : true) // spring actuator needs power to maintain non-default state && (manualcontrol && lowvoltagepower ? false == valve.is_disabled : true) // needs power to change state, without it just pass through && (manualcontrol && lowvoltagepower ? false == pantographCircuit.allDown : true) && - (lineBreaker.closed || false == lineBreaker.pantographsRequireIt) // fed through the closed line breaker, where it comes first + (lineBreaker.IsClosed() || false == lineBreaker.config.pantographsRequireIt) // fed through the closed line breaker, where it comes first && (valve.is_active || (manualcontrol && lowvoltagepower && valve.is_enabled) || (autostart && lowvoltagepower)); // shouldn't ever get this far but, eh auto const pantographexists{EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.PhysicalLayout & 1 << pant_id}; @@ -805,7 +735,7 @@ void physics::Vehicle::GensetCheck(double const Deltatime) } else { - auto const demand{GensetSelected() && lineBreaker.closed ? std::clamp(inductionMotor.forceShare, 0.0, 1.0) : 0.0}; + auto const demand{GensetSelected() && lineBreaker.IsClosed() ? std::clamp(inductionMotor.forceShare, 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) @@ -920,7 +850,7 @@ bool physics::Vehicle::CompartmentLightsSwitchOff(bool State, range_t const Noti bool physics::Vehicle::MainSwitch(bool const State, range_t const Notify) { - bool const initialstate{lineBreaker.closed || diesel.startupRequested}; + bool const initialstate{lineBreaker.IsClosed() || diesel.startupRequested}; MainSwitch_(State); @@ -931,19 +861,19 @@ bool physics::Vehicle::MainSwitch(bool const State, range_t const Notify) SendCtrlToNext(VehicleCommand::mainSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return (lineBreaker.closed || diesel.startupRequested) != initialstate; + return (lineBreaker.IsClosed() || diesel.startupRequested) != initialstate; } void physics::Vehicle::MainSwitch_(bool const State) { - if (lineBreaker.closed == State || MainCtrlPosNo == 0) + if (lineBreaker.IsClosed() == State || MainCtrlPosNo == 0) { // nothing to do return; } - bool const initialstate{lineBreaker.closed}; + bool const initialstate{lineBreaker.IsClosed()}; if (false == State || true == MainSwitchCheck()) { @@ -959,18 +889,18 @@ void physics::Vehicle::MainSwitch_(bool const State) else { // additional check, as vehicles without pantographs won't fail relay checks earlier - lineBreaker.closed = true; + lineBreaker.Close(); } } else { - lineBreaker.closed = false; + lineBreaker.Open(); // potentially knock out the pumps if their switch doesn't force them on WaterPump.is_active &= WaterPump.is_enabled; FuelPump.is_active &= FuelPump.is_enabled; } - if (lineBreaker.closed != initialstate) + if (lineBreaker.IsClosed() != initialstate) { LastSwitchingTime = 0; Timer::subsystem.switching.note(Timer::switching_counter::mains, this, &TypeName, &Name); @@ -991,11 +921,11 @@ bool physics::Vehicle::MainSwitchCheck() const powerisavailable = Genset.is_active && Genset.voltage >= TractionSupplyMinVoltage(); } - return powerisavailable && (ScndCtrlPos == 0 || EngineType == ElectricInductionMotor) && lineBreaker.initCountdown <= 0.0 && - (converter.overloaded == false || converter.overloadRelayOffWithLineBreaker) && true == protection.ground && (true == protection.noVoltage || lineBreaker.pantographsRequireIt) && true == protection.overvoltage && + return powerisavailable && (ScndCtrlPos == 0 || EngineType == ElectricInductionMotor) && lineBreaker.IsInitialised() && + (converter.IsOverloaded() == false || converter.config.overloadRelayOffWithLineBreaker) && true == protection.GroundHolds() && (true == protection.UndervoltageHolds() || lineBreaker.config.pantographsRequireIt) && true == protection.OvervoltageHolds() && LastSwitchingTime > CtrlDelay && (HasCamshaft ? IsMainCtrlActualNoPowerPos() : - lineBreaker.closesOnlyAtNoPower ? IsMainCtrlNoPowerPos() : + lineBreaker.config.closesOnlyAtNoPower ? IsMainCtrlNoPowerPos() : true) && false == DamageFlag.HasAll(VehicleDamage::derailed) && false == TestFlag(EngDmgFlag, 1) && false == EmergencyBrakeHoldsMainOff(); } @@ -1007,19 +937,16 @@ bool physics::Vehicle::MainSwitchCheck() const bool physics::Vehicle::ConverterSwitch(bool State, range_t const Notify) { - auto const initialstate{converter.allow}; + auto const initialstate{converter.IsAllowed()}; - if (converter.start == start_t::manual) - { - converter.allow = State; - } + converter.Switch(State); if (Notify != range_t::local) { SendCtrlToNext(VehicleCommand::converterSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return converter.allow != initialstate; + return converter.IsAllowed() != initialstate; } bool physics::Vehicle::HeatingSwitch(bool const State, range_t const Notify) @@ -1116,11 +1043,11 @@ double physics::Vehicle::EnginePowerSourceVoltage() const // blowers, the traction motors bool physics::Vehicle::MainCircuitPowered() const { - if (false == lineBreaker.closed) + if (false == lineBreaker.IsClosed()) { return false; } - if (false == lineBreaker.pantographsRequireIt || EnginePowerSource.SourceType != TPowerSource::CurrentCollector) + if (false == lineBreaker.config.pantographsRequireIt || EnginePowerSource.SourceType != TPowerSource::CurrentCollector) { // the closed line breaker says it all: the undervoltage trip opens it without traction voltage, and an engine // which runs is its own supply diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index f75fb011f..3f7556b72 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -909,15 +909,15 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) {"Battery", battery}, {"Converter", converter}, {"Direction", direction}}; // main circuit - extract_value(lineBreaker.initTime, "MainInitTime", line, ""); + extract_value(lineBreaker.config.initTime, "MainInitTime", line, ""); { auto lookup = starts.find(extract_value("MainStart", line)); - lineBreaker.start = lookup != starts.end() ? lookup->second : manual; + lineBreaker.config.start = lookup != starts.end() ? lookup->second : manual; } - extract_value(lineBreaker.pantographsRequireIt, "PantRequiresMain", line, ""); + extract_value(lineBreaker.config.pantographsRequireIt, "PantRequiresMain", line, ""); // the brake pipe pressure of an emergency brake application, which opens the line breaker under power - extract_value(lineBreaker.emergencyOffPressure, "EmergencyBrakeMainOff", line, ""); - lineBreaker.emergencyOffPressure = std::max(0.0, lineBreaker.emergencyOffPressure); + extract_value(lineBreaker.config.emergencyOffPressure, "EmergencyBrakeMainOff", line, ""); + lineBreaker.config.emergencyOffPressure = std::max(0.0, lineBreaker.config.emergencyOffPressure); // battery { auto lookup = starts.find(extract_value("BatteryStart", line)); @@ -926,10 +926,10 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) // converter { auto lookup = starts.find(extract_value("ConverterStart", line)); - this->converter.start = lookup != starts.end() ? lookup->second : manual; + this->converter.config.start = lookup != starts.end() ? lookup->second : manual; } - extract_value(this->converter.startDelay, "ConverterStartDelay", line, ""); - extract_value(this->converter.overloadRelayOffWithLineBreaker, "ConverterOverloadWhenMainIsOff", line, TrainType == train_type::emu ? "yes" : "no"); + extract_value(this->converter.config.startDelay, "ConverterStartDelay", line, ""); + extract_value(this->converter.config.overloadRelayOffWithLineBreaker, "ConverterOverloadWhenMainIsOff", line, TrainType == train_type::emu ? "yes" : "no"); // compressor { auto lookup = starts.find(extract_value("CompressorStart", line)); @@ -995,7 +995,7 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) std::map> const interlocks{{"Converter", line_contactors_interlock::converter}, {"MotorBlowers", line_contactors_interlock::motor_blowers}}; auto lookup = interlocks.find(extract_value("LineContactorsInterlock", line)); - lineContactors.interlock = lookup != interlocks.end() ? lookup->second : line_contactors_interlock::none; + lineContactors.config.interlock = lookup != interlocks.end() ? lookup->second : line_contactors_interlock::none; } extract_value(LouvresOpenPressure, "LouvresOpenPressure", line, ""); // compartment lights @@ -1007,14 +1007,14 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) { auto lookup = starts.find(extract_value("GroundRelayStart", line)); auto const defaultstart{TrainType == train_type::emu ? automatic : manual}; - protection.groundStart = lookup != starts.end() ? lookup->second : defaultstart; + protection.config.groundStart = 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 == train_type::emu ? converter : manual}; - this->converter.overloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart; + this->converter.config.overloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart; } } @@ -1183,7 +1183,7 @@ void physics::Vehicle::LoadFIZ_Engine(std::string const &Input) { EngineType = LoadFIZ_EngineDecode(extract_value("EngineType", Input)); - extract_value(lineBreaker.jointStart, "JointEngineStart", Input, ""); + extract_value(lineBreaker.config.jointStart, "JointEngineStart", Input, ""); if (std::string transmission = extract_value("Trans", Input); false == transmission.empty()) { @@ -1262,9 +1262,9 @@ void physics::Vehicle::LoadFIZ_Engine(std::string const &Input) extract_value(MotorBlowers[VehicleEnd::front].min_start_velocity, "MotorBlowersStartVelocity", Input, ""); MotorBlowers[VehicleEnd::rear] = MotorBlowers[VehicleEnd::front]; // pressure switch - extract_value(protection.hasPressureSwitch, "PressureSwitch", Input, TrainType != train_type::emu ? "yes" : "no"); + extract_value(protection.config.hasPressureSwitch, "PressureSwitch", Input, TrainType != train_type::emu ? "yes" : "no"); // its brake cylinder half; the brake pipe one stays - extract_value(protection.pressureSwitchWatchesCylinders, "PressureSwitchBrakeCylinder", Input, ""); + extract_value(protection.config.pressureSwitchWatchesCylinders, "PressureSwitchBrakeCylinder", Input, ""); } // Engine: of a diesel engine, its revolutions, gears, hydraulic transmission and retarder @@ -1469,13 +1469,13 @@ void physics::Vehicle::LoadFIZ_Switches(std::string const &Input) { extract_value(pantographCircuit.switchType, "Pantograph", Input, ""); - extract_value(converter.switchType, "Converter", Input, ""); - extract_value(lineContactors.switchType, "MotorConnectors", Input, ""); + extract_value(converter.config.switchType, "Converter", Input, ""); + extract_value(lineContactors.config.switchType, "MotorConnectors", Input, ""); trainHeating.switchImpulse = ToLower(extract_value("TrainHeating", Input)) == "impulse"; // because people can't make up their minds whether it's "impulse" or "Impulse"... pantographCircuit.switchType = ToLower(pantographCircuit.switchType); - converter.switchType = ToLower(converter.switchType); - lineContactors.switchType = ToLower(lineContactors.switchType); + converter.config.switchType = ToLower(converter.config.switchType); + lineContactors.config.switchType = ToLower(lineContactors.config.switchType); // universal reset buttons assignments extract_value(UniversalResetButtonFlag[0], "RelayResetButton1", Input, ""); extract_value(UniversalResetButtonFlag[1], "RelayResetButton2", Input, ""); diff --git a/physics/components/maincircuit.h b/physics/components/maincircuit.h index 3970b2835..39f083687 100644 --- a/physics/components/maincircuit.h +++ b/physics/components/maincircuit.h @@ -8,7 +8,12 @@ http://mozilla.org/MPL/2.0/. */ // the main circuit of a vehicle: the line breaker, the line contactors, the protective relays, the converter. Held by -// physics::Vehicle as lineBreaker, lineContactors, protection and converter +// physics::Vehicle as lineBreaker, lineContactors, protection and converter. +// +// each part holds its definition in `config`, filled from the .fiz and not changed after, and keeps its state to itself: +// the rest of the vehicle reads the state through the queries and changes it through the operations. what decides when +// they act (the interlocks of the cab, the controller positions, the voltages) stays with the vehicle, which hands the +// parts what they need as plain values #pragma once @@ -20,69 +25,265 @@ namespace physics { // the line breaker (the main switch) of the vehicle -struct LineBreaker +class LineBreaker { - bool closed = false; - double initTime{0.0}; // how long the main circuit initialises after it gets its power, before the breaker can close [s] + public: + struct Config + { + double initTime{0.0}; // how long the main circuit initialises after it gets its power, before the breaker can close [s] + start_t start{start_t::manual}; + // Engine:JointEngineStart: the line breaker / engine start switch of the cab works the vehicles in multiple too; when it + // doesn't, the cab has separate switches for them (mainb_*, mainc_*) + bool jointStart{true}; + // Cntrl.PantRequiresMain: the line breaker closes without traction voltage and holds without it, and the pantographs + // rise and stay up only while it's closed (EU05, EP05, ČD 181 family); off, the pantographs come first and the line + // breaker needs their voltage. what the main circuit feeds still needs the voltage (MainCircuitPowered()), and without + // it the undervoltage relay opens the line contactors (protection.UndervoltageHolds()) + bool pantographsRequireIt{false}; + bool closesOnlyAtNoPower{false}; // it closes only with the master controller at a position of no power + // 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 (pantographsRequireIt) they drop with it (EP05). 0: an emergency + // application leaves the line breaker alone + double emergencyOffPressure{0.0}; + }; + Config config; + + bool IsClosed() const { return closed; } + void Close() { closed = true; } + void Open() { closed = false; } + + // how long the main circuit still initialises [s]; below zero once it's done + double RemainingInitTime() const { return initCountdown; } + // the main circuit is done initialising, the breaker may close + bool IsInitialised() const { return initCountdown <= 0.0; } + // the step of the supply of the main circuit: with it the initialisation counts down, without it it starts over. + // returns whether the circuit has its supply and was done initialising before this step, when it may start on its own + bool UpdateInitialisation(bool const supplied, double const dt) + { + if (false == supplied) + { + initCountdown = config.initTime; + return false; + } + // NOTE: readiness means a countdown below zero, which rules out at once the vehicles of no initialisation time + if (initCountdown >= 0.0) + { + initCountdown -= dt; + return false; + } + return true; + } + + private: + bool closed{false}; double initCountdown{0.0}; // how long it still initialises [s] - start_t start{start_t::manual}; - // Engine:JointEngineStart: the line breaker / engine start switch of the cab works the vehicles in multiple too; when it - // doesn't, the cab has separate switches for them (mainb_*, mainc_*) - bool jointStart{true}; - // Cntrl.PantRequiresMain: the line breaker closes without traction voltage and holds without it, and the pantographs - // rise and stay up only while it's closed (EU05, EP05, ČD 181 family); off, the pantographs come first and the line - // breaker needs their voltage. what the main circuit feeds still needs the voltage (MainCircuitPowered()), and without - // it the undervoltage relay opens the line contactors (protection.noVoltage) - bool pantographsRequireIt{false}; - bool closesOnlyAtNoPower{false}; // it closes only with the master controller at a position of no power - // 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 (pantographsRequireIt) they drop with it (EP05). 0: an emergency - // application leaves the line breaker alone - double emergencyOffPressure{0.0}; }; // the line contactors of the traction motors -struct LineContactors +class LineContactors { - bool closed = false; - bool forcedOpen{false}; // the button that forces them open - std::string switchType; // StLinSwitchType: the kind of the switch of the cab - line_contactors_interlock interlock{line_contactors_interlock::none}; // what else they need to close - double lastSwitchTime = 0.0; // the time since they last switched [s] + public: + struct Config + { + std::string switchType; // StLinSwitchType: the kind of the switch of the cab + line_contactors_interlock interlock{line_contactors_interlock::none}; // what else they need to close + }; + Config config; + + bool IsClosed() const { return closed; } + void Close() { closed = true; } + void Open() { closed = false; } + + // the button of the cab that forces them open + bool IsForcedOpen() const { return forcedOpen; } + void ForceOpen(bool const State) { forcedOpen = State; } + + // the time since the master controller or the relays of the start last switched [s] + double TimeSinceSwitch() const { return lastSwitchTime; } + void RestartSwitchTimer() { lastSwitchTime = 0.0; } + void AdvanceSwitchTimer(double const dt) { lastSwitchTime += dt; } + + private: + bool closed{false}; + bool forcedOpen{false}; + double lastSwitchTime{0.0}; }; -// the protective relays and the pressure switch of the main circuit -struct ProtectionRelays +// the protective relays and the pressure switch of the main circuit. the relays hold (true) while all is well and drop +// (false) when they protect the circuit +class ProtectionRelays { - // the undervoltage relay: it switches off if the voltage drops below its threshold, which opens the line breaker; with - // lineBreaker.pantographsRequireIt it opens the line contactors instead, and switches back on only with the master + public: + struct Config + { + start_t groundStart{start_t::manual}; // how the ground relay is reset + bool hasPressureSwitch{true}; + // Engine:PressureSwitchBrakeCylinder: 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 pressureSwitchWatchesCylinders{true}; + }; + Config config; + + // the undervoltage relay: it drops if the voltage falls below its threshold, which opens the line breaker; with + // lineBreaker.config.pantographsRequireIt it opens the line contactors instead, and picks up again only with the master // controller at zero or the first position + bool UndervoltageHolds() const { return noVoltage; } + // the overvoltage relay, which drops above the voltage it's set to + bool OvervoltageHolds() const { return overvoltage; } + // the voltage relays as the drive of the vehicle judges them from the voltage of its supply + void SetVoltageRelays(bool const undervoltageHolds, bool const overvoltageHolds) + { + noVoltage = undervoltageHolds; + overvoltage = overvoltageHolds; + } + + // the ground relay, which drops to protect against damage from earths + bool GroundHolds() const { return ground; } + // the ground relay of a series motor vehicle in the step: it drops without the low voltage, and one that isn't reset + // by hand picks up again with it + void UpdateGround(bool const lowVoltagePower) + { + ground &= lowVoltagePower; + if (config.groundStart != start_t::manual) + { + // NOTE: we're ignoring intricaties of battery and converter types as they're unlikely to be used + // TODO: generic check method which takes these into account + ground |= lowVoltagePower; + } + } + // the reset of the ground relay, which needs the low voltage; returns whether it picked up + bool ResetGround(bool const lowVoltagePower) + { + auto const reset{false == ground && lowVoltagePower}; + ground |= lowVoltagePower; + return reset; + } + + // tripped while the brake pipe and/or the brake cylinders aren't at their working pressures + bool PressureSwitchTripped() const { return pressureSwitch; } + // the pressure switch in the step, from the pressures [bar] + void UpdatePressureSwitch(double const cylinderPressure, double const pipePressure) + { + pressureSwitch = config.hasPressureSwitch && ((config.pressureSwitchWatchesCylinders && cylinderPressure > 2.0) || pipePressure < 3.6); + } + + private: bool noVoltage{true}; - bool overvoltage{true}; // the overvoltage relay, which opens above the voltage it's set to - bool ground{true}; // the ground relay, which opens to protect against damage from earths - start_t groundStart{start_t::manual}; // how the ground relay is reset - bool pressureSwitch{false}; // tripped while the brake pipe and/or the brake cylinders aren't at their working pressures - bool hasPressureSwitch{true}; - // Engine:PressureSwitchBrakeCylinder: 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 pressureSwitchWatchesCylinders{true}; + bool overvoltage{true}; + bool ground{true}; + bool pressureSwitch{false}; +}; + +// what the converter of the vehicle needs to know in the step +struct ConverterSupply +{ + bool lineBreakerClosed{false}; + bool lowVoltage24v{false}; // the 24 V circuits have their power + bool directionActive{false}; // the reverser is set + bool pantographPressureLock{false}; // the pressure lock of the pantographs is on + bool highVoltage{false}; // the main circuit, or for a vehicle of no power of its own the train line, has its voltage + bool damaged{false}; // the converter is damaged }; // the converter of the vehicle -struct PowerConverter +class PowerConverter { - start_t start{start_t::manual}; // whether it is started by hand, or another way - float startDelay{0.0f}; // the delay before it starts, once its conditions are met [s] + public: + struct Config + { + start_t start{start_t::manual}; // whether it is started by hand, or another way + float startDelay{0.0f}; // the delay before it starts, once its conditions are met [s] + start_t overloadRelayStart{start_t::manual}; // whether its overload relay is reset by a button of its own + bool overloadRelayOffWithLineBreaker{false}; // ConverterOverloadRelayOffWhenMainIsOff + std::string switchType; // ConvSwitchType: the kind of the switch of the cab. TODO: the kinds of the switches belong to the cab definition + }; + Config config; + + bool IsRunning() const { return running; } + // it may run, as its switch (or its start) has it + bool IsAllowed() const { return allow; } + // the switch of the converter, where it is worked by hand; returns whether that changed it + bool Switch(bool const State) + { + auto const initialstate{allow}; + if (config.start == start_t::manual) + { + allow = State; + } + return allow != initialstate; + } + // the switch of the vehicle itself; most have none, so it allows + bool LocalSwitchOn() const { return allowLocal; } + void SetLocalSwitch(bool const State) { allowLocal = State; } + + // the overload relay of the converter and the heating + bool IsOverloaded() const { return overloaded; } + void Overload() { overloaded = true; } + // the reset of the overload relay, which needs the low voltage; returns whether it was tripped + bool ResetOverloadRelay(bool const lowVoltagePower) + { + auto const reset{overloaded && lowVoltagePower}; + overloaded &= false == lowVoltagePower; + return reset; + } + + // the converter in the step + void Update(ConverterSupply const &supply, double const dt) + { + if (config.start != start_t::disabled && config.overloadRelayOffWithLineBreaker) + { + overloaded |= false == supply.lineBreakerClosed && supply.lowVoltage24v; + } + switch (config.start) + { + case start_t::disabled: + allow = false; + // NOTE: if there's no converter in vehicle we can end the check here + return; + case start_t::automatic: + allow = supply.lineBreakerClosed; + break; + case start_t::direction: + allow = supply.directionActive; + break; + default: + break; + } + if (allow && allowLocal && false == overloaded && false == supply.pantographPressureLock && supply.highVoltage) + { + // delay timer can be optionally configured, and is set anew whenever converter goes off + if (startDelayTimer <= 0.0) + { + running = true; + } + else + { + startDelayTimer -= dt; + } + } + else + { + running = false; + startDelayTimer = static_cast(config.startDelay); + } + if (config.overloadRelayStart == start_t::converter && false == (allow && allowLocal) && false == supply.damaged) + { + // reset converter overload relay if the converter was switched off, unless it's damaged + overloaded = false; + } + } + + // for the tests of the parts it feeds: the converter running, or not, whatever its conditions + void SetRunningForTest(bool const State) { running = State; } + + private: + bool allow{false}; + bool allowLocal{true}; + bool running{false}; + bool overloaded{false}; double startDelayTimer{0.0}; // how long its conditions have been met - bool allow = false; // it may run - bool allowLocal{true}; // the switch of the vehicle itself; most have none, so it allows - bool running = false; - start_t overloadRelayStart{start_t::manual}; // whether its overload relay is reset by a button of its own - bool overloadRelayOffWithLineBreaker{false}; // ConverterOverloadRelayOffWhenMainIsOff - bool overloaded = false; // the overload relay of the converter and the heating tripped - std::string switchType; // ConvSwitchType: the kind of the switch of the cab. TODO: the kinds of the switches belong to the cab definition }; } // namespace physics diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 62cd30bb3..886ce0cd7 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -518,7 +518,7 @@ bool physics::Vehicle::BrakeReleaser(int state) if (state != 0) { // additional limitations imposed by pressure switch - if (false == protection.pressureSwitch || false == ReleaserEnabledOnlyAtNoPowerPos || true == IsMainCtrlNoPowerPos()) + if (false == protection.PressureSwitchTripped() || false == ReleaserEnabledOnlyAtNoPowerPos || true == IsMainCtrlNoPowerPos()) { brakes.distributor->Releaser(state); } @@ -794,7 +794,7 @@ void physics::Vehicle::CompressorCheck(double dt) { case CompressorSupply::converter: { - air.compressor.allow = converter.allow; + air.compressor.allow = converter.IsAllowed(); break; } case CompressorSupply::engine: diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index cf25d9509..0feef1456 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -97,12 +97,12 @@ double physics::Vehicle::Current(double n, double U) } } - if (brakes.electrodynamic.on && !FuseFlag && brakes.electrodynamic.type == dbrake_automatic && lowVoltage.power110vAvailable && lineBreaker.closed) // hamowanie EP09 //TUHEX + if (brakes.electrodynamic.on && !FuseFlag && brakes.electrodynamic.type == dbrake_automatic && lowVoltage.power110vAvailable && lineBreaker.IsClosed()) // hamowanie EP09 //TUHEX { // TODO: zrobic bardziej uniwersalne nie tylko dla EP09 MotorCurrent = -std::max(motor_param(0).fi * (Vadd / (Vadd + motor_param(0).Isat) - motor_param(0).fi0), 0.) * n * 2.0 / brakes.electrodynamic.resistance; } - else if (RList[MainCtrlActualPos].Bn == 0 || false == lineContactors.closed) + else if (RList[MainCtrlActualPos].Bn == 0 || false == lineContactors.IsClosed()) { // wylaczone MotorCurrent = 0; @@ -447,7 +447,7 @@ bool physics::Vehicle::TractionModeSwitch(traction_mode const Mode, range_t cons { 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 == lineBreaker.closed}; + auto const accepted{false == lineBreaker.IsClosed()}; if (Genset.fitted() && accepted) { @@ -668,7 +668,7 @@ void physics::Vehicle::VoltageRelaysCheck() void physics::Vehicle::DumbTractionForce(double const PosRatio) { - if (lineBreaker.closed && CabActive != 0) + if (lineBreaker.IsClosed() && CabActive != 0) { if (Vel > 0.1) { @@ -1461,12 +1461,11 @@ bool physics::Vehicle::RelayReset(int const Relays, range_t const Notify) bool reset{false}; if (TestFlag(Relays, relay_t::maincircuitground) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && - (protection.groundStart == start_t::manual || protection.groundStart == start_t::manualwithautofallback) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && + (protection.config.groundStart == start_t::manual || protection.config.groundStart == start_t::manualwithautofallback) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && !TestFlag(EngDmgFlag, 1)) { // NOTE: true means the relay is operational - reset |= !protection.ground && lowvoltagepower; - protection.ground |= lowvoltagepower; + reset |= protection.ResetGround(lowvoltagepower); } if (TestFlag(Relays, relay_t::tractionnmotoroverload) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && @@ -1479,15 +1478,14 @@ bool physics::Vehicle::RelayReset(int const Relays, range_t const Notify) FuseFlag &= !lowvoltagepower; } - if (TestFlag(Relays, relay_t::primaryconverteroverload) && converter.overloadRelayStart == start_t::manual + if (TestFlag(Relays, relay_t::primaryconverteroverload) && converter.config.overloadRelayStart == start_t::manual // && ( false == Mains ) - && false == converter.allow) + && false == converter.IsAllowed()) { // NOTE: false means the relay is operational // TODO: cleanup, flip the FuseFlag code to match other relays // TODO: check whether the power is required, TBD, TODO: make it configurable? - reset |= converter.overloaded && lowvoltagepower; - converter.overloaded &= !lowvoltagepower; + reset |= converter.ResetOverloadRelay(lowvoltagepower); } if (reset) diff --git a/physics/vehicle.h b/physics/vehicle.h index d106a243c..2cc62bc21 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -1516,13 +1516,13 @@ class Vehicle // the pressure switch, when fitted, cuts the start off and puts them out, otherwise they go out once the brakes are applied bool MainCircuitLampsEnabled() const { - return false == protection.pressureSwitch && (protection.hasPressureSwitch || brakes.cylinderPressure < 1.0); + return false == protection.PressureSwitchTripped() && (protection.config.hasPressureSwitch || brakes.cylinderPressure < 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 lineBreaker.emergencyOffPressure > 0.0 && brakePipe.pressure < lineBreaker.emergencyOffPressure && false == IsMainCtrlNoPowerPos(); + return lineBreaker.config.emergencyOffPressure > 0.0 && brakePipe.pressure < lineBreaker.config.emergencyOffPressure && 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 @@ -1531,15 +1531,15 @@ class Vehicle { if (EngineType == TEngineType::DieselElectric) { - return false == lineContactors.closed; + return false == lineContactors.IsClosed(); } - return false == lineContactors.closed && MainCircuitLampsEnabled(); + return false == lineContactors.IsClosed() && MainCircuitLampsEnabled(); } // the vehicles the line breaker / engine start switch of this vehicle works, and its engine stopping on its own // stops: the whole consist, or with JointEngineStart=No this vehicle alone (eu07/maszyna#80) range_t MainSwitchRange() const { - return lineBreaker.jointStart ? range_t::consist : range_t::local; + return lineBreaker.config.jointStart ? range_t::consist : range_t::local; } // whether the pneumatic louvres of the motor fans are still closed, the main reservoir short of the pressure that opens them bool LouvresClosed() const @@ -1552,7 +1552,7 @@ class Vehicle // the AI driver doesn't leave it so: the converters of the other vehicles running, it would wait for the contactors forever bool LineContactorsHeldByLocalConverterSwitch() const { - return lineContactors.interlock == line_contactors_interlock::converter && false == converter.allowLocal; + return lineContactors.config.interlock == line_contactors_interlock::converter && false == converter.LocalSwitchOn(); } // whether the vehicle has a driver's cab: it has the driver's brake valve (BrakeHandle in the Cntrl. section of the // .fiz), which the wagons and most cars of the units without a cab don't (a few copy the Cntrl. section of the cab diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 7af23b625..568e8ba97 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -73,9 +73,9 @@ blackbox::driver driver_of(TDynamicObject const &Vehicle) { std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle const &Controlling) { namespace device = blackbox::cab_devices; auto const on{[](bool const State, std::uint32_t const Bit) { return State ? Bit : 0u; }}; - return on(Occupied.lowVoltage.batteryOn || Controlling.lowVoltage.batteryOn, device::battery) | on(Controlling.lineBreaker.closed, device::main_breaker) | + return on(Occupied.lowVoltage.batteryOn || Controlling.lowVoltage.batteryOn, device::battery) | on(Controlling.lineBreaker.IsClosed(), device::main_breaker) | on(Controlling.pantographs[VehicleEnd::front].is_active, device::pantograph_front) | on(Controlling.pantographs[VehicleEnd::rear].is_active, device::pantograph_rear) | - on(Controlling.converter.running, device::converter) | on(Controlling.air.compressor.running, device::compressor) | on(Controlling.lineContactors.closed, device::line_contactors) | + on(Controlling.converter.IsRunning(), device::converter) | on(Controlling.air.compressor.running, device::compressor) | on(Controlling.lineContactors.IsClosed(), device::line_contactors) | on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose, device::sanding) | on(Occupied.WarningSignal != 0, device::horn) | on(false == Occupied.Doors.instances[VehicleSide::left].is_closed, device::doors_left) | on(false == Occupied.Doors.instances[VehicleSide::right].is_closed, device::doors_right) | on(Occupied.Radio, device::radio) | diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index 74fcfb9d7..dbba5d1d5 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -89,8 +89,8 @@ bool is_ready(driven const &Driven) { auto const air{physics.air.mainReservoirVolume <= 0.0 || physics.mainPipe.pressure >= 4.5}; // the converter feeds the 110 V circuits (the electrodynamic brake's control among them); the AI switches // it on once the line breaker is closed, so a train already charged with air isn't ready before it runs - auto const converter{physics.converter.start != start_t::manual || physics.converter.running}; - return physics.lineBreaker.closed && air && converter; + auto const converter{physics.converter.config.start != start_t::manual || physics.converter.IsRunning()}; + return physics.lineBreaker.IsClosed() && air && converter; } namespace { @@ -174,7 +174,7 @@ bool start_up(driven Driven, track const &Track, double Seconds, trace *Trace) { if (diesel) { prepare_diesel(Driven); } - if (controlling.lineBreaker.pantographsRequireIt && false == controlling.lineBreaker.closed) { + if (controlling.lineBreaker.config.pantographsRequireIt && false == controlling.lineBreaker.IsClosed()) { // the pantographs rise only through the closed line breaker, which closes without their voltage for (int i = 0; i < 3 && cab.DirActive <= 0; ++i) { cab.DirectionForward(); @@ -189,7 +189,7 @@ bool start_up(driven Driven, track const &Track, double Seconds, trace *Trace) { for (int i = 0; i < 3 && cab.DirActive <= 0; ++i) { cab.DirectionForward(); } - if (false == controlling.lineBreaker.closed) { + if (false == controlling.lineBreaker.IsClosed()) { close_line_breaker(Driven); } else { @@ -210,7 +210,7 @@ void drive_cycle(driven Driven, track const &Track, trace &Trace) { auto &cab{Driven.cab}; auto &controlling{Driven.controlling}; if (false == start_up(Driven, Track, 300.0, &Trace)) { - MESSAGE("didn't get ready: Mains " << controlling.lineBreaker.closed << ", main reservoir " << controlling.mainPipe.pressure); + MESSAGE("didn't get ready: Mains " << controlling.lineBreaker.IsClosed() << ", main reservoir " << controlling.mainPipe.pressure); } Trace.mark("release brakes"); release_brakes(cab); diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index e1769511c..e252ff90f 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -55,7 +55,7 @@ std::vector motion() { std::vector traction() { return { - {"Mains", [](auto const &M) { return M.lineBreaker.closed ? 1.0 : 0.0; }}, + {"Mains", [](auto const &M) { return M.lineBreaker.IsClosed() ? 1.0 : 0.0; }}, {"DirActive", [](auto const &M) { return M.DirActive; }}, {"MainCtrlPos", [](auto const &M) { return M.MainCtrlPos; }}, {"MainCtrlActualPos", [](auto const &M) { return M.MainCtrlActualPos; }}, diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index 1942c476a..f85c88105 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -70,15 +70,15 @@ std::vector const &invariants() { [](auto const &M, double, auto const *) { return M.air.compressor.maxPressure <= 0.0 || M.air.mainReservoirPressure <= 1.01 * M.air.compressor.maxPressure + pressure_margin; }, [](auto const &M) { return values({{"Compressor", M.air.mainReservoirPressure}, {"MaxCompressor", M.air.compressor.maxPressure}}); }}, {"no motor current with the line breaker open", - [](auto const &M, double, auto const *) { return M.lineBreaker.closed || false == electric(M) || std::abs(M.Im) < 1.0; }, - [](auto const &M) { return values({{"Mains", M.lineBreaker.closed}, {"Im", M.Im}, {"Itot", M.Itot}}); }}, + [](auto const &M, double, auto const *) { return M.lineBreaker.IsClosed() || false == electric(M) || std::abs(M.Im) < 1.0; }, + [](auto const &M) { return values({{"Mains", M.lineBreaker.IsClosed()}, {"Im", M.Im}, {"Itot", M.Itot}}); }}, {"no motor current with the line contactors open, but for the dynamic brake", [](auto const &M, double, auto const *) { // the dynamic brake closes its own circuit of the motors and the resistors - return M.lineContactors.closed || M.brakes.electrodynamic.on || M.EngineType != TEngineType::ElectricSeriesMotor || std::abs(M.Im) < 1.0; + return M.lineContactors.IsClosed() || M.brakes.electrodynamic.on || M.EngineType != TEngineType::ElectricSeriesMotor || std::abs(M.Im) < 1.0; }, [](auto const &M) { - return values({{"StLinFlag", M.lineContactors.closed}, {"DynamicBrakeFlag", M.brakes.electrodynamic.on}, {"Im", M.Im}, {"MainCtrlActualPos", M.MainCtrlActualPos}}); + return values({{"StLinFlag", M.lineContactors.IsClosed()}, {"DynamicBrakeFlag", M.brakes.electrodynamic.on}, {"Im", M.Im}, {"MainCtrlActualPos", M.MainCtrlActualPos}}); }}, {"no tractive force without power", [](auto const &M, double, auto const *) { return M.Power >= 0.01 || std::abs(M.Ft) < 1.0; }, diff --git a/tests/unit/scenario.cpp b/tests/unit/scenario.cpp index ecda46e3e..568ade19a 100644 --- a/tests/unit/scenario.cpp +++ b/tests/unit/scenario.cpp @@ -11,7 +11,7 @@ namespace { // switch is on when the controller leaves zero doesn't close its line contactors until the controller is back at zero bool start_cut_off(consist &Train) { for (std::size_t i = 0; i < Train.size(); ++i) { - if (Train[i].physics().protection.pressureSwitch) { + if (Train[i].physics().protection.PressureSwitchTripped()) { return true; } } @@ -74,7 +74,7 @@ void scenario::full_power(double Seconds) { wait(1.0); } controlling.IncMainCtrl(1); - for (int i = 0; i < 90 && false == controlling.lineContactors.closed; ++i) { + for (int i = 0; i < 90 && false == controlling.lineContactors.IsClosed(); ++i) { wait(1.0); } for (int i = 0; i < 60 && false == controlling.IsMainCtrlMaxPowerPos(); ++i) { diff --git a/tests/unit/test_6dg_power_steps.cpp b/tests/unit/test_6dg_power_steps.cpp index ed3f3c7fa..1df7f30ca 100644 --- a/tests/unit/test_6dg_power_steps.cpp +++ b/tests/unit/test_6dg_power_steps.cpp @@ -61,8 +61,8 @@ void get_ready(vehicle &Loco, test::track const &Track) { test::drive(driven, Track, 1.0); move_to(Loco, hold); test::drive(driven, Track, 5.0); - REQUIRE(Loco->lineBreaker.closed); // the engine running - REQUIRE(Loco->lineContactors.closed); // the line contactors closed + REQUIRE(Loco->lineBreaker.IsClosed()); // the engine running + REQUIRE(Loco->lineContactors.IsClosed()); // 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)); } diff --git a/tests/unit/test_auxiliaries.cpp b/tests/unit/test_auxiliaries.cpp index 6334179c8..5df40fd95 100644 --- a/tests/unit/test_auxiliaries.cpp +++ b/tests/unit/test_auxiliaries.cpp @@ -16,7 +16,7 @@ std::vector auxiliaries() { return { {"BatteryVoltage", [](auto const &M) { return M.lowVoltage.batteryVoltage; }}, {"Battery", [](auto const &M) { return M.lowVoltage.batteryOn ? 1.0 : 0.0; }}, - {"ConverterFlag", [](auto const &M) { return M.converter.running ? 1.0 : 0.0; }}, + {"ConverterFlag", [](auto const &M) { return M.converter.IsRunning() ? 1.0 : 0.0; }}, {"Power110vIsAvailable", [](auto const &M) { return M.lowVoltage.power110vAvailable ? 1.0 : 0.0; }}, {"PantPress", [](auto const &M) { return M.pantographAir.pressure; }}, {"PantVolume", [](auto const &M) { return M.pantographAir.volume; }}, @@ -43,10 +43,10 @@ TEST_CASE("auxiliaries: the battery drained by the lights and the pantographs' c eu07.pantographAir.compressorRunning = true; scenario.wait(30.0); CHECK(eu07.lowVoltage.batteryVoltage < 0.83 * eu07.lowVoltage.nominalBatteryVoltage); - CHECK(eu07.lineBreaker.closed); + CHECK(eu07.lineBreaker.IsClosed()); scenario.wait(5000.0); CHECK(eu07.lowVoltage.batteryVoltage < eu07.lowVoltage.nominalBatteryVoltage / 1.57); - CHECK_FALSE(eu07.lineBreaker.closed); + CHECK_FALSE(eu07.lineBreaker.IsClosed()); scenario.act("start up again"); CHECK_FALSE(scenario.start_up()); CHECK(eu07.lowVoltage.batteryVoltage < eu07.lowVoltage.nominalBatteryVoltage / 1.57); @@ -99,7 +99,7 @@ TEST_CASE("auxiliaries: the pantographs on their own tank, leaking until the pre scenario.wait(600.0); CHECK(eu07.pantographAir.pressure < eu07.EnginePowerSource.CollectorParameters.MinPress); CHECK_FALSE(eu07.pantographAir.pressureSwitchActive); - CHECK_FALSE(eu07.lineBreaker.closed); + CHECK_FALSE(eu07.lineBreaker.IsClosed()); scenario.act("small compressor on"); eu07.pantographAir.compressorRunning = true; for (int i = 0; i < 60 && eu07.pantographAir.compressorRunning; ++i) { diff --git a/tests/unit/test_camshaft.cpp b/tests/unit/test_camshaft.cpp index 11b2784d6..2c8a580d9 100644 --- a/tests/unit/test_camshaft.cpp +++ b/tests/unit/test_camshaft.cpp @@ -70,20 +70,22 @@ definition skoda() { void running(physics::Vehicle &Locomotive, int const Direction, int const Position, int const Controller) { Locomotive.CabActive = 1; Locomotive.DirActive = Direction; - Locomotive.lineBreaker.closed = true; + Locomotive.lineBreaker.Close(); Locomotive.brakePipe.pressure = 5.0; // bar, the pressure switch lets the line contactors close Locomotive.brakes.cylinderPressure = 0.0; - Locomotive.lineContactors.closed = true; + Locomotive.lineContactors.Close(); Locomotive.MainCtrlActualPos = Position; Locomotive.MainCtrlPos = Controller; - Locomotive.lineContactors.lastSwitchTime = 10.0; + Locomotive.lineContactors.RestartSwitchTimer(); + Locomotive.lineContactors.AdvanceSwitchTimer(10.0); } // steps the camshaft as the physics does, each step once the delay since the previous one passed; returns where it // ended up int run_camshaft(physics::Vehicle &Locomotive, int const Steps) { for (int step = 0; step < Steps; ++step) { - Locomotive.lineContactors.lastSwitchTime = 10.0; + Locomotive.lineContactors.RestartSwitchTimer(); + Locomotive.lineContactors.AdvanceSwitchTimer(10.0); Locomotive.AutoRelayCheck(); } return Locomotive.MainCtrlActualPos; @@ -108,7 +110,7 @@ TEST_CASE("camshaft: running backwards, the camshaft goes back down from the las running(physics, -1, 22, 0); run_camshaft(physics, 30); CHECK(physics.MainCtrlActualPos == 0); - CHECK_FALSE(physics.lineContactors.closed); // the motors don't pull any more + CHECK_FALSE(physics.lineContactors.IsClosed()); // the motors don't pull any more } } diff --git a/tests/unit/test_cntrl.cpp b/tests/unit/test_cntrl.cpp index eb99d05b0..eba42f832 100644 --- a/tests/unit/test_cntrl.cpp +++ b/tests/unit/test_cntrl.cpp @@ -23,18 +23,18 @@ TEST_CASE("cntrl: the relays of a multiple unit start on their own, of other veh SUBCASE("multiple unit") { vehicle unit{definition::load("wagon").set("Param", "Type", "ezt")}; REQUIRE(unit->TrainType == train_type::emu); - CHECK(unit->protection.groundStart == start_t::automatic); - CHECK(unit->converter.overloadRelayStart == start_t::converter); // activates when the converter is switched off + CHECK(unit->protection.config.groundStart == start_t::automatic); + CHECK(unit->converter.config.overloadRelayStart == start_t::converter); // activates when the converter is switched off } SUBCASE("other vehicle") { vehicle wagon{definition::load("wagon")}; - CHECK(wagon->protection.groundStart == start_t::manual); - CHECK(wagon->converter.overloadRelayStart == start_t::manual); + CHECK(wagon->protection.config.groundStart == start_t::manual); + CHECK(wagon->converter.config.overloadRelayStart == start_t::manual); } SUBCASE("given in the definition") { vehicle unit{definition::load("wagon").set("Param", "Type", "ezt").set("Cntrl", "GroundRelayStart", "Manual").set("Cntrl", "ConverterOverloadRelayStart", "Automatic")}; - CHECK(unit->protection.groundStart == start_t::manual); - CHECK(unit->converter.overloadRelayStart == start_t::automatic); + CHECK(unit->protection.config.groundStart == start_t::manual); + CHECK(unit->converter.config.overloadRelayStart == start_t::automatic); } } diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 108cf87e2..8bbb0a18b 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -596,7 +596,7 @@ TEST_CASE("collisions: a locomotive at its starting effort against a braked trai }; // 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->lineContactors.closed; ++i) { + for (int i = 0; i < 90 && false == locomotive->lineContactors.IsClosed(); ++i) { test::drive(driver, line, 1.0); } for (int i = 0; i < 60 && false == locomotive->IsMainCtrlMaxPowerPos(); ++i) { @@ -1248,7 +1248,7 @@ TEST_CASE("collisions: a locomotive pushing a standing braked train at full powe }; // 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->lineContactors.closed; ++i) { + for (int i = 0; i < 90 && false == locomotive->lineContactors.IsClosed(); ++i) { test::drive(driver, line, 1.0); } for (int i = 0; i < 60 && false == locomotive->IsMainCtrlMaxPowerPos(); ++i) { diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index 58ad83fa3..f4e2c4841 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -28,7 +28,7 @@ std::vector state() { std::vector result{ {"MainCtrlPos", [](auto const &M) { return M.MainCtrlPos; }}, {"ScndCtrlPos", [](auto const &M) { return M.ScndCtrlPos; }}, - {"LastRelayTime", [](auto const &M) { return M.lineContactors.lastSwitchTime; }}, + {"LastRelayTime", [](auto const &M) { return M.lineContactors.TimeSinceSwitch(); }}, {"eimic_real", [](auto const &M) { return M.eimic_real; }}, {"TUHEX_StageActual", [](auto const &M) { return M.TUHEX_StageActual; }}, {"TUHEX_Active", [](auto const &M) { return flag(M.TUHEX_Active); }}, @@ -46,14 +46,14 @@ std::vector state() { {"OilPumpDisabled", [](auto const &M) { return flag(M.OilPump.is_disabled); }}, {"CompartmentLightsEnabled", [](auto const &M) { return flag(M.CompartmentLights.is_enabled); }}, {"CompartmentLightsDisabled", [](auto const &M) { return flag(M.CompartmentLights.is_disabled); }}, - {"MainSwitch", [](auto const &M) { return flag(M.lineBreaker.closed); }}, + {"MainSwitch", [](auto const &M) { return flag(M.lineBreaker.IsClosed()); }}, {"Heating", [](auto const &M) { return flag(M.trainHeating.on); }}, {"DirActive", [](auto const &M) { return M.DirActive; }}, {"DirAbsolute", [](auto const &M) { return M.DirAbsolute; }}, {"CabActive", [](auto const &M) { return M.CabActive; }}, {"CabMaster", [](auto const &M) { return flag(M.CabMaster); }}, {"AutoRelayFlag", [](auto const &M) { return flag(M.AutoRelayFlag); }}, - {"ConverterAllow", [](auto const &M) { return flag(M.converter.allow); }}, + {"ConverterAllow", [](auto const &M) { return flag(M.converter.IsAllowed()); }}, {"Battery", [](auto const &M) { return flag(M.lowVoltage.batteryOn); }}, {"CompressorAllow", [](auto const &M) { return flag(M.air.compressor.allow); }}, {"CompressorListPos", [](auto const &M) { return M.air.compressor.listPosition; }}, @@ -411,8 +411,8 @@ TEST_CASE("commands: every switch of the cab, worked on a pair standing under th {"PantFrontActive", [](auto const &M) { return flag(M.pantographs[VehicleEnd::front].is_active); }}, {"PantRearActive", [](auto const &M) { return flag(M.pantographs[VehicleEnd::rear].is_active); }}, {"PantPress", [](auto const &M) { return M.pantographAir.pressure; }}, - {"GroundRelay", [](auto const &M) { return flag(M.protection.ground); }}, - {"ConverterFlag", [](auto const &M) { return flag(M.converter.running); }}, + {"GroundRelay", [](auto const &M) { return flag(M.protection.GroundHolds()); }}, + {"ConverterFlag", [](auto const &M) { return flag(M.converter.IsRunning()); }}, {"CompressorFlag", [](auto const &M) { return flag(M.air.compressor.running); }}, {"Compressor", [](auto const &M) { return M.air.mainReservoirPressure; }}, {"MainCtrlActualPos", [](auto const &M) { return M.MainCtrlActualPos; }}, diff --git a/tests/unit/test_compressor.cpp b/tests/unit/test_compressor.cpp index 13e667ceb..b9c8bc6fc 100644 --- a/tests/unit/test_compressor.cpp +++ b/tests/unit/test_compressor.cpp @@ -47,14 +47,14 @@ TEST_CASE("compressor: without a start delay the compressor starts with its powe run_compressor(vehicle, 1.0); REQUIRE_FALSE(vehicle->air.compressor.running); // no power, no compressor - vehicle->lineBreaker.closed = true; + vehicle->lineBreaker.Close(); run_compressor(vehicle, step); CHECK(vehicle->air.compressor.running); } TEST_CASE("compressor: the compressor starts the delay after getting its power") { auto vehicle{compressor_vehicle(5.0)}; - vehicle->lineBreaker.closed = true; + vehicle->lineBreaker.Close(); run_compressor(vehicle, 4.9); CHECK_FALSE(vehicle->air.compressor.running); @@ -68,15 +68,15 @@ TEST_CASE("compressor: the compressor starts the delay after getting its power") TEST_CASE("compressor: the delay starts over once the power is gone") { auto vehicle{compressor_vehicle(5.0)}; - vehicle->lineBreaker.closed = true; + vehicle->lineBreaker.Close(); run_compressor(vehicle, 10.0); REQUIRE(vehicle->air.compressor.running); - vehicle->lineBreaker.closed = false; // the engine stopped + vehicle->lineBreaker.Open(); // the engine stopped run_compressor(vehicle, 1.0); CHECK_FALSE(vehicle->air.compressor.running); - vehicle->lineBreaker.closed = true; // and started again + vehicle->lineBreaker.Close(); // and started again run_compressor(vehicle, 4.9); CHECK_FALSE(vehicle->air.compressor.running); run_compressor(vehicle, 0.2); @@ -85,7 +85,7 @@ TEST_CASE("compressor: the delay starts over once the power is gone") { TEST_CASE("compressor: a compressor fed from the low voltage waits from the low voltage coming on") { auto vehicle{compressor_vehicle(5.0, "")}; // the default supply: the converter, the 110 V - vehicle->lineBreaker.closed = true; // which alone doesn't feed it + vehicle->lineBreaker.Close(); // which alone doesn't feed it run_compressor(vehicle, 10.0); REQUIRE_FALSE(vehicle->air.compressor.running); @@ -98,7 +98,7 @@ TEST_CASE("compressor: a compressor fed from the low voltage waits from the low TEST_CASE("compressor: the pressure switch stops the compressor above the cut-out pressure") { auto vehicle{compressor_vehicle(0.0)}; - vehicle->lineBreaker.closed = true; + vehicle->lineBreaker.Close(); vehicle->air.compressedVolume = 8.5; // over MaxCP, in the reservoir of 1 m3 run_compressor(vehicle, step); CHECK(vehicle->air.compressor.governorLock); @@ -107,7 +107,7 @@ TEST_CASE("compressor: the pressure switch stops the compressor above the cut-ou TEST_CASE("compressor: without a pressure switch the air over the cut-out pressure is vented") { auto vehicle{compressor_vehicle(0.0, "Main", 8.0)}; // MinCP the same as MaxCP: no pressure switch - vehicle->lineBreaker.closed = true; + vehicle->lineBreaker.Close(); vehicle->air.compressedVolume = 8.5; run_compressor(vehicle, step); REQUIRE(vehicle->air.compressor.running); // nothing stops it @@ -116,13 +116,13 @@ TEST_CASE("compressor: without a pressure switch the air over the cut-out pressu TEST_CASE("compressor: an engine stopped before the delay passed counts the whole delay again") { auto vehicle{compressor_vehicle(30.0)}; - vehicle->lineBreaker.closed = true; // engine started + vehicle->lineBreaker.Close(); // engine started run_compressor(vehicle, 20.0); REQUIRE_FALSE(vehicle->air.compressor.running); - vehicle->lineBreaker.closed = false; // engine stopped, 10 s short of the delay + vehicle->lineBreaker.Open(); // engine stopped, 10 s short of the delay run_compressor(vehicle, 1.0); - vehicle->lineBreaker.closed = true; + vehicle->lineBreaker.Close(); run_compressor(vehicle, 15.0); // 36 s since the first start, but only 15 s since this one CHECK_FALSE(vehicle->air.compressor.running); @@ -134,7 +134,7 @@ TEST_CASE("compressor: the start delay holds back a compressor switched on by ha auto vehicle{compressor_vehicle(30.0)}; vehicle->air.compressor.start = start_t::manual; vehicle->air.compressor.allow = true; // switch in the cabinet on before the engine start - vehicle->lineBreaker.closed = true; + vehicle->lineBreaker.Close(); run_compressor(vehicle, 29.9); CHECK_FALSE(vehicle->air.compressor.running); @@ -175,12 +175,12 @@ definition generator_vehicle(double const ConverterDelay, double const Compresso TEST_CASE("compressor: fed from the converter it waits for the converter start delay") { vehicle loco{generator_vehicle(30.0, 0.0)}; REQUIRE(loco->air.compressor.supply == physics::CompressorSupply::converter); - REQUIRE(loco->converter.startDelay == doctest::Approx(30.0)); + REQUIRE(loco->converter.config.startDelay == doctest::Approx(30.0)); loco.run(1.0); // engine off CHECK_FALSE(loco->lowVoltage.power110vAvailable); - loco->lineBreaker.closed = true; // engine started + loco->lineBreaker.Close(); // engine started loco.run(25.0); CHECK_FALSE(loco->lowVoltage.power110vAvailable); CHECK_FALSE(loco->air.compressor.running); @@ -195,7 +195,7 @@ TEST_CASE("compressor: fed from the converter the start delay counts from the co REQUIRE(loco->air.compressor.startDelay == doctest::Approx(10.0)); loco.run(1.0); // engine off - loco->lineBreaker.closed = true; // engine started + loco->lineBreaker.Close(); // engine started loco.run(25.0); REQUIRE(loco->lowVoltage.power110vAvailable); // the converter is up CHECK_FALSE(loco->air.compressor.running); // but the compressor waits for its own delay as well diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp index a850194fd..042f02c39 100644 --- a/tests/unit/test_crew.cpp +++ b/tests/unit/test_crew.cpp @@ -31,7 +31,7 @@ void get_under_way(consist &Train, int const Position, double const Seconds) { } test::drive(driver, line, 20.0); driver.controlling.IncMainCtrl(1); - for (int i = 0; i < 90 && false == driver.controlling.lineContactors.closed; ++i) { + for (int i = 0; i < 90 && false == driver.controlling.lineContactors.IsClosed(); ++i) { test::drive(driver, line, 1.0); } for (int i = 0; i < 60 && driver.controlling.MainCtrlPos < Position; ++i) { @@ -194,7 +194,7 @@ TEST_CASE("crew: a locomotive under power left by its driver stops and stays bra auto &eu07{train[0].physics()}; REQUIRE(train[0].speed() > 20.0); REQUIRE(eu07.MainCtrlPos > 0); - REQUIRE(eu07.lineBreaker.closed); + REQUIRE(eu07.lineBreaker.IsClosed()); crew::secure(eu07, eu07); @@ -213,7 +213,7 @@ TEST_CASE("crew: a locomotive under power left by its driver stops and stays bra // 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.lineBreaker.closed); + CHECK(eu07.lineBreaker.IsClosed()); CHECK(eu07.Im == doctest::Approx(0.0)); } diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 786d16f1b..b2c1e7759 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -59,7 +59,7 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { } REQUIRE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(eu07vehicle->Derailed == dr::outcome::overturned); - CHECK_FALSE(eu07vehicle->lineBreaker.closed); + CHECK_FALSE(eu07vehicle->lineBreaker.IsClosed()); // 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); diff --git a/tests/unit/test_engine_shutdown.cpp b/tests/unit/test_engine_shutdown.cpp index 4e54206ed..b96aa011c 100644 --- a/tests/unit/test_engine_shutdown.cpp +++ b/tests/unit/test_engine_shutdown.cpp @@ -27,7 +27,7 @@ TEST_CASE("engine shutdown: the shunter starts with the starter button") { auto shunter{running_shunter()}; REQUIRE(shunter->EngineType == TEngineType::DieselEngine); REQUIRE(shunter->FuelPump.start_type == start_t::automatic); - CHECK(shunter->lineBreaker.closed); + CHECK(shunter->lineBreaker.IsClosed()); CHECK(shunter->FuelPump.is_active); CHECK(shunter->enrot > 0.9 * shunter->diesel.minRevolutions); } @@ -36,11 +36,11 @@ TEST_CASE("engine shutdown: neither the fuel pump switch nor the battery switch auto shunter{running_shunter()}; shunter->FuelPumpSwitchOff(true, range_t::local); // the pump started automatically ignores its switch shunter.run(10.0); - CHECK(shunter->lineBreaker.closed); + CHECK(shunter->lineBreaker.IsClosed()); shunter->BatterySwitch(false); shunter.run(10.0); CHECK(shunter->lowVoltage.power110vAvailable); // the converter run by the engine keeps feeding the fuel pump - CHECK(shunter->lineBreaker.closed); + CHECK(shunter->lineBreaker.IsClosed()); CHECK(shunter->enrot > 0.9 * shunter->diesel.minRevolutions); } @@ -49,7 +49,7 @@ TEST_CASE("engine shutdown: the command opening the main circuit stops the engin REQUIRE(shunter->MainCircuitOpensWithStarterOnly()); // the cab passes the command on with only the starter button CHECK(shunter->MainSwitch(false)); shunter.run(20.0); - CHECK_FALSE(shunter->lineBreaker.closed); + CHECK_FALSE(shunter->lineBreaker.IsClosed()); CHECK_FALSE(shunter->FuelPump.is_active); CHECK(shunter->enrot == 0.0); } @@ -61,7 +61,7 @@ TEST_CASE("engine shutdown: the engine starts again after it was stopped") { REQUIRE(shunter->enrot == 0.0); shunter->MainSwitch(true); shunter.run(15.0); - CHECK(shunter->lineBreaker.closed); + CHECK(shunter->lineBreaker.IsClosed()); CHECK(shunter->enrot > 0.9 * shunter->diesel.minRevolutions); } diff --git a/tests/unit/test_engine_start.cpp b/tests/unit/test_engine_start.cpp index c45019b71..1f7e1c684 100644 --- a/tests/unit/test_engine_start.cpp +++ b/tests/unit/test_engine_start.cpp @@ -39,7 +39,7 @@ void prepare(consist &Train) { } bool running(physics::Vehicle const &Vehicle) { - return Vehicle.lineBreaker.closed && Vehicle.enrot > 0.5 * Vehicle.diesel.minRevolutions; + return Vehicle.lineBreaker.IsClosed() && Vehicle.enrot > 0.5 * Vehicle.diesel.minRevolutions; } // the time step of the train in the loops below @@ -65,8 +65,8 @@ TEST_CASE("engine start: the joint start is the default, and JointEngineStart=No consist train; auto const &joint{train.add(sn61(), 1).physics()}; auto const &separate{train.add(sn61(false)).physics()}; - CHECK(joint.lineBreaker.jointStart); - CHECK_FALSE(separate.lineBreaker.jointStart); + CHECK(joint.lineBreaker.config.jointStart); + CHECK_FALSE(separate.lineBreaker.config.jointStart); CHECK(joint.MainSwitchRange() == range_t::consist); CHECK(separate.MainSwitchRange() == range_t::local); } @@ -120,16 +120,16 @@ TEST_CASE("engine start: by default the cab's switch starts and stops the engine auto &first{train.add(sn61(), 1).physics()}; auto const &second{train.add(sn61()).physics()}; prepare(train); - REQUIRE_FALSE(first.lineBreaker.closed); - REQUIRE_FALSE(second.lineBreaker.closed); + REQUIRE_FALSE(first.lineBreaker.IsClosed()); + REQUIRE_FALSE(second.lineBreaker.IsClosed()); first.MainSwitch(true, first.MainSwitchRange()); train.run(15.0); CHECK(running(first)); CHECK(running(second)); first.MainSwitch(false, first.MainSwitchRange()); train.run(5.0); - CHECK_FALSE(first.lineBreaker.closed); - CHECK_FALSE(second.lineBreaker.closed); + CHECK_FALSE(first.lineBreaker.IsClosed()); + CHECK_FALSE(second.lineBreaker.IsClosed()); } TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch") { @@ -142,8 +142,8 @@ TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch first.MainSwitch(true, first.MainSwitchRange()); train.run(15.0); REQUIRE(running(first)); - CHECK_FALSE(second.lineBreaker.closed); - CHECK_FALSE(third.lineBreaker.closed); + CHECK_FALSE(second.lineBreaker.IsClosed()); + CHECK_FALSE(third.lineBreaker.IsClosed()); // the second one's switch, mainb_*, starts the second engine engine_start::remote_switch switchb; @@ -155,7 +155,7 @@ TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch hold(train, switchb, engineb, 2.0); // past the SN61's delay of 1.5 s train.run(15.0); CHECK(running(second)); - CHECK_FALSE(third.lineBreaker.closed); + CHECK_FALSE(third.lineBreaker.IsClosed()); // and the third one's, mainc_*, the third hold(train, switchc, enginec, 2.0); train.run(15.0); @@ -164,12 +164,12 @@ TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch // the switches open their own vehicles' circuits only CHECK(engine_start::remote_switch::open(second)); train.run(5.0); - CHECK_FALSE(second.lineBreaker.closed); + CHECK_FALSE(second.lineBreaker.IsClosed()); CHECK(running(first)); CHECK(running(third)); first.MainSwitch(false, first.MainSwitchRange()); train.run(5.0); - CHECK_FALSE(first.lineBreaker.closed); + CHECK_FALSE(first.lineBreaker.IsClosed()); CHECK(running(third)); CHECK_FALSE(engine_start::remote_switch::open(second)); // already stopped } @@ -184,7 +184,7 @@ TEST_CASE("engine start: the switch of another vehicle is held for the vehicle's // without the battery the switch does nothing, however long it's held hold(train, switchb, &second, 5.0); train.run(5.0); - CHECK_FALSE(second.lineBreaker.closed); + CHECK_FALSE(second.lineBreaker.IsClosed()); CHECK_FALSE(second.diesel.startupRequested); prepare(train); @@ -245,7 +245,7 @@ TEST_CASE("engine start: an engine stopping on its own stops the others only whe // the first one's fuel cut off, its engine stops first.FuelPump.is_disabled = true; train.run(15.0); - CHECK_FALSE(first.lineBreaker.closed); + CHECK_FALSE(first.lineBreaker.IsClosed()); CHECK(first.enrot == 0.0); // started on their own, the others keep running CHECK(running(second) == (false == joint)); @@ -275,7 +275,7 @@ TEST_CASE("engine start: an engine stopped from its own switch doesn't stop the // mainb_off CHECK(engine_start::remote_switch::open(second)); train.run(30.0); - CHECK_FALSE(second.lineBreaker.closed); + CHECK_FALSE(second.lineBreaker.IsClosed()); CHECK(second.enrot == 0.0); CHECK(running(first)); CHECK(running(third)); @@ -287,12 +287,12 @@ TEST_CASE("engine start: the stopped engine of the cab's vehicle doesn't stop th auto &first{train.add(sn61(), 1).physics()}; auto &second{train.add(sn61(false)).physics()}; prepare(train); - REQUIRE_FALSE(first.lineBreaker.closed); + REQUIRE_FALSE(first.lineBreaker.IsClosed()); // mainb_on engine_start::remote_switch switchb; hold(train, switchb, engine_start::engine(first, first, 2), 2.0); train.run(15.0); CHECK(running(second)); - CHECK_FALSE(first.lineBreaker.closed); + CHECK_FALSE(first.lineBreaker.IsClosed()); CHECK(first.enrot == 0.0); } diff --git a/tests/unit/test_field_shunting.cpp b/tests/unit/test_field_shunting.cpp index e1c2c9b8f..e761e59d7 100644 --- a/tests/unit/test_field_shunting.cpp +++ b/tests/unit/test_field_shunting.cpp @@ -55,7 +55,7 @@ TEST_CASE("field shunting: the SU45 with its switch, off at full power and switc scenario.get_going(); scenario.full_power(120.0); CHECK(su45.IsMainCtrlMaxPowerPos()); - CHECK(su45.lineContactors.closed); + CHECK(su45.lineContactors.IsClosed()); CHECK(su45.ScndCtrlPos == 0); CHECK_FALSE(su45.IncScndCtrl(1)); scenario.wait(1.0); @@ -87,7 +87,7 @@ TEST_CASE("field shunting: a diesel-electric with AutoRelay=Optional alone shunt scenario.get_going(); scenario.full_power(120.0); CHECK(su45.IsMainCtrlMaxPowerPos()); - CHECK(su45.lineContactors.closed); + CHECK(su45.lineContactors.IsClosed()); // over 50 km/h: the relays don't shunt, the driver does CHECK(su45.Vel > 50.0); CHECK(su45.ScndCtrlPos == 0); diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index b51264712..1c32112ba 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -80,7 +80,7 @@ bool start_on_genset(vehicle &Vehicle, track const &Track = no_wire, double cons wake(cab); cab.TractionModeSwitch(traction_mode::genset); cab.GensetSwitch(true); - if (false == cab.lineBreaker.closed) { + if (false == cab.lineBreaker.IsClosed()) { if (cab.MainSwitchCheck()) { close_line_breaker(cab); } @@ -90,7 +90,7 @@ bool start_on_genset(vehicle &Vehicle, track const &Track = no_wire, double cons cab.CompressorSwitch(true); } run(Vehicle, 1.0, Track); - if (cab.lineBreaker.closed && cab.converter.running && cab.mainPipe.pressure >= 4.5) { + if (cab.lineBreaker.IsClosed() && cab.converter.IsRunning() && cab.mainPipe.pressure >= 4.5) { // and the brakes let go test::release_brakes(cab); for (auto wait = 0; wait < 120 && cab.brakes.cylinderPressure > 0.05; ++wait) { @@ -193,13 +193,13 @@ TEST_CASE("genset: the selector moves only with the line breaker open") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; auto &cab{dragon6.physics()}; REQUIRE(test::start_up(test::driving(dragon6), wire)); - REQUIRE(cab.lineBreaker.closed); + REQUIRE(cab.lineBreaker.IsClosed()); CHECK_FALSE(cab.TractionModeSwitch(traction_mode::genset)); CHECK(cab.TractionMode == traction_mode::catenary); run(dragon6, 2.0, wire); - CHECK(cab.lineBreaker.closed); + CHECK(cab.lineBreaker.IsClosed()); cab.MainSwitch(false); - REQUIRE_FALSE(cab.lineBreaker.closed); + REQUIRE_FALSE(cab.lineBreaker.IsClosed()); CHECK(cab.TractionModeSwitch(traction_mode::genset)); CHECK(cab.GensetSelected()); CHECK(cab.TractionModeSwitch(traction_mode::catenary)); @@ -223,19 +223,19 @@ TEST_CASE("genset: started, it closes the line breaker without a catenary") { 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.lineBreaker.closed; ++second) { + for (auto second = 0; second < 10 && false == cab.lineBreaker.IsClosed(); ++second) { if (cab.MainSwitchCheck()) { close_line_breaker(cab); } run(dragon6, 1.0); } - REQUIRE(cab.lineBreaker.closed); + REQUIRE(cab.lineBreaker.IsClosed()); CHECK(cab.pantographCircuit.supplyVoltage == 0.0); dragon6.step(no_wire); CHECK(cab.EngineVoltage == 3000.0); CHECK(cab.MainCircuitPowered()); run(dragon6, 5.0); - CHECK(cab.lineBreaker.closed); + CHECK(cab.lineBreaker.IsClosed()); } TEST_CASE("genset: on the catenary position the genset feeds nothing") { @@ -248,7 +248,7 @@ TEST_CASE("genset: on the catenary position the genset feeds nothing") { CHECK(cab.TractionMode == traction_mode::catenary); CHECK_FALSE(cab.MainSwitchCheck()); close_line_breaker(cab); - CHECK_FALSE(cab.lineBreaker.closed); + CHECK_FALSE(cab.lineBreaker.IsClosed()); dragon6.step(no_wire); CHECK(cab.EngineVoltage == 0.0); CHECK(cab.TractionSupplyVoltage() == 0.0); @@ -264,7 +264,7 @@ TEST_CASE("genset: on the genset position the catenary feeds nothing") { // 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.pantographCircuit.supplyVoltage > 2900.0); - CHECK_FALSE(cab.lineBreaker.closed); + CHECK_FALSE(cab.lineBreaker.IsClosed()); CHECK_FALSE(cab.MainSwitchCheck()); dragon6.step(wire); CHECK(cab.EngineVoltage == 0.0); @@ -280,7 +280,7 @@ TEST_CASE("genset: the power at the wheels stays within the genset's") { auto revolutions{0.0}; auto over{0L}; auto step_count{0L}; - for (; step_count < 60000 && cab.Vel < 80.0 && cab.lineBreaker.closed; ++step_count) { + for (; step_count < 60000 && cab.Vel < 80.0 && cab.lineBreaker.IsClosed(); ++step_count) { step(dragon6, step_count); auto const power{wheel_power(cab)}; peak = std::max(peak, power); @@ -291,7 +291,7 @@ TEST_CASE("genset: the power at the wheels stays within the genset's") { } CAPTURE(step_count); CAPTURE(peak); - CHECK(cab.lineBreaker.closed); + CHECK(cab.lineBreaker.IsClosed()); CHECK(cab.Vel >= 80.0); CHECK(over == 0); CHECK(peak <= genset_traction_power * 1.02); @@ -382,13 +382,13 @@ TEST_CASE("genset: stopped, it opens the line breaker") { REQUIRE(cab.Genset.revolutions == doctest::Approx(cab.Genset.revolutions_idle)); cab.GensetSwitch(false); auto step_count{0L}; - for (; step_count < 1000 && cab.lineBreaker.closed; ++step_count) { + for (; step_count < 1000 && cab.lineBreaker.IsClosed(); ++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.lineBreaker.closed); + CHECK_FALSE(cab.lineBreaker.IsClosed()); 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 @@ -396,7 +396,7 @@ TEST_CASE("genset: stopped, it opens the line breaker") { close_line_breaker(cab); run(dragon6, 1.0); } - CHECK_FALSE(cab.lineBreaker.closed); + CHECK_FALSE(cab.lineBreaker.IsClosed()); // 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); @@ -448,18 +448,18 @@ TEST_CASE("genset: the pantographs' pressure switch leaves the genset's line bre cab.pantographAir.pressureSwitchActive = true; cab.pantographAir.pressure = 0.0; cab.PantPressureSwitchCheck(); - CHECK(cab.lineBreaker.closed); + CHECK(cab.lineBreaker.IsClosed()); } 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.physics()}; REQUIRE(test::start_up(test::driving(dragon6), wire)); - REQUIRE(cab.lineBreaker.closed); + REQUIRE(cab.lineBreaker.IsClosed()); // the pressure switch looks at the voltage through the couplers, not the pantographs' cab.pantographAir.pressureSwitchActive = true; cab.pantographAir.pressure = 0.0; cab.PantPressureSwitchCheck(); - CHECK_FALSE(cab.lineBreaker.closed); + CHECK_FALSE(cab.lineBreaker.IsClosed()); } } @@ -508,7 +508,7 @@ TEST_CASE("genset: braking electrodynamically on the genset sends nothing back") REQUIRE(braked.electrodynamic); CHECK(braked.lowest_current >= -1e-6); CHECK(braked.speed_lost > 5.0); - CHECK(dragon6->lineBreaker.closed); + CHECK(dragon6->lineBreaker.IsClosed()); } SUBCASE("on the catenary the same braking feeds the line, the check the genset is spared") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; @@ -543,12 +543,12 @@ TEST_CASE("genset: one genset feeds the next car through the high voltage coupli 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.lineBreaker.closed); + CHECK(second.lineBreaker.IsClosed()); // stopped, the genset takes the voltage away first.GensetSwitch(false); train.run(30.0, no_wire); CHECK(second.GetTrainsetHighVoltage() < 1.0); - CHECK_FALSE(second.lineBreaker.closed); + CHECK_FALSE(second.lineBreaker.IsClosed()); } TEST_CASE("genset: the selector command travels along the train") { @@ -580,10 +580,10 @@ TEST_CASE("genset: a selector command refused with the line breaker closed isn't auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).physics()}; auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).physics()}; REQUIRE(test::start_up(test::driving(train), wire)); - REQUIRE(first.lineBreaker.closed); + REQUIRE(first.lineBreaker.IsClosed()); // the second one's line breaker opened by itself, the lead's is closed second.MainSwitch(false, range_t::local); - REQUIRE_FALSE(second.lineBreaker.closed); + REQUIRE_FALSE(second.lineBreaker.IsClosed()); CHECK_FALSE(first.TractionModeSwitch(traction_mode::genset, range_t::consist)); CHECK_FALSE(first.GensetSelected()); CHECK_FALSE(second.GensetSelected()); diff --git a/tests/unit/test_line_contactors.cpp b/tests/unit/test_line_contactors.cpp index 90f3ff2a1..4429189d6 100644 --- a/tests/unit/test_line_contactors.cpp +++ b/tests/unit/test_line_contactors.cpp @@ -9,7 +9,7 @@ namespace { test::vehicle locomotive(bool const Pressureswitch) { test::vehicle vehicle{test::definition::load("wagon").set("Engine", "PressureSwitch", Pressureswitch)}; - vehicle->lineContactors.closed = false; // the line contactors open + vehicle->lineContactors.Open(); // the line contactors open vehicle->brakePipe.pressure = 5.0; return vehicle; } @@ -18,16 +18,16 @@ test::vehicle locomotive(bool const Pressureswitch) { TEST_CASE("line contactors: with a pressure switch the lamp goes out with the start cut off") { auto vehicle{locomotive(true)}; - REQUIRE(vehicle->protection.hasPressureSwitch); + REQUIRE(vehicle->protection.config.hasPressureSwitch); vehicle->brakes.cylinderPressure = 1.5; // braked, the start can still be made vehicle->MotorConnectorsCheck(); // updates the pressure switch - REQUIRE_FALSE(vehicle->protection.pressureSwitch); + REQUIRE_FALSE(vehicle->protection.PressureSwitchTripped()); CHECK(vehicle->LineContactorsLampLit()); vehicle->brakes.cylinderPressure = 2.5; // the pressure switch cuts the start off vehicle->MotorConnectorsCheck(); - REQUIRE(vehicle->protection.pressureSwitch); + REQUIRE(vehicle->protection.PressureSwitchTripped()); CHECK_FALSE(vehicle->LineContactorsLampLit()); } @@ -43,7 +43,7 @@ TEST_CASE("line contactors: without a pressure switch the lamp goes out with the TEST_CASE("line contactors: closed contactors put the lamp out") { auto vehicle{locomotive(true)}; - vehicle->lineContactors.closed = true; + vehicle->lineContactors.Close(); CHECK_FALSE(vehicle->LineContactorsLampLit()); } @@ -85,19 +85,19 @@ test::vehicle diesel_electric() { TEST_CASE("line contactors: on a diesel-electric the lamp is lit at 0 and goes out on a power position") { auto vehicle{diesel_electric()}; REQUIRE(vehicle->EngineType == TEngineType::DieselElectric); - REQUIRE(vehicle->lineBreaker.closed); - REQUIRE_FALSE(vehicle->protection.pressureSwitch); - CHECK_FALSE(vehicle->lineContactors.closed); + REQUIRE(vehicle->lineBreaker.IsClosed()); + REQUIRE_FALSE(vehicle->protection.PressureSwitchTripped()); + CHECK_FALSE(vehicle->lineContactors.IsClosed()); CHECK(vehicle->LineContactorsLampLit()); vehicle->IncMainCtrl(1); vehicle.run(3.0); - CHECK(vehicle->lineContactors.closed); + CHECK(vehicle->lineContactors.IsClosed()); CHECK_FALSE(vehicle->LineContactorsLampLit()); vehicle->DecMainCtrl(1); vehicle.run(3.0); - CHECK_FALSE(vehicle->lineContactors.closed); + CHECK_FALSE(vehicle->lineContactors.IsClosed()); CHECK(vehicle->LineContactorsLampLit()); } @@ -107,12 +107,12 @@ TEST_CASE("line contactors: on a diesel-electric the lamp lights with the contac vehicle.run(1.0); vehicle->IncMainCtrl(1); vehicle.run(2.0); - REQUIRE(vehicle->lineContactors.closed); + REQUIRE(vehicle->lineContactors.IsClosed()); vehicle.hold_brake_pipe(2.5); // bar, below the 3.6 bar of the pressure switch vehicle.run(10.0); - REQUIRE(vehicle->protection.pressureSwitch); - CHECK_FALSE(vehicle->lineContactors.closed); + REQUIRE(vehicle->protection.PressureSwitchTripped()); + CHECK_FALSE(vehicle->lineContactors.IsClosed()); CHECK(vehicle->LineContactorsLampLit()); // it went out here CHECK_FALSE(vehicle->MainCircuitLampsEnabled()); // the ground relay and overload lamps still go out with the start cut off @@ -120,11 +120,11 @@ TEST_CASE("line contactors: on a diesel-electric the lamp lights with the contac // they close again only on the first one vehicle.hold_brake_pipe(5.0); vehicle.run(60.0); - REQUIRE_FALSE(vehicle->protection.pressureSwitch); - CHECK_FALSE(vehicle->lineContactors.closed); + REQUIRE_FALSE(vehicle->protection.PressureSwitchTripped()); + CHECK_FALSE(vehicle->lineContactors.IsClosed()); CHECK(vehicle->LineContactorsLampLit()); vehicle->DecMainCtrl(1); vehicle.run(3.0); - CHECK(vehicle->lineContactors.closed); + CHECK(vehicle->lineContactors.IsClosed()); CHECK_FALSE(vehicle->LineContactorsLampLit()); } diff --git a/tests/unit/test_line_contactors_interlock.cpp b/tests/unit/test_line_contactors_interlock.cpp index eb92812e2..94e658281 100644 --- a/tests/unit/test_line_contactors_interlock.cpp +++ b/tests/unit/test_line_contactors_interlock.cpp @@ -22,7 +22,7 @@ vehicle ready(std::string_view const Interlock) { loaded.set("Cntrl", "LineContactorsInterlock", std::string{Interlock}); } vehicle locomotive{loaded}; - locomotive->lineBreaker.closed = true; + locomotive->lineBreaker.Close(); locomotive->DirActive = 1; locomotive->brakePipe.pressure = 5.0; locomotive->brakes.cylinderPressure = 0.0; @@ -34,15 +34,15 @@ test::track const line{0.15, 0.0, test::catenary_3kv}; } // namespace TEST_CASE("line contactors interlock: read from the Cntrl. section, none by default") { - CHECK(ready("")->lineContactors.interlock == line_contactors_interlock::none); - CHECK(ready("Converter")->lineContactors.interlock == line_contactors_interlock::converter); - CHECK(ready("MotorBlowers")->lineContactors.interlock == line_contactors_interlock::motor_blowers); - CHECK(ready("Something")->lineContactors.interlock == line_contactors_interlock::none); + CHECK(ready("")->lineContactors.config.interlock == line_contactors_interlock::none); + CHECK(ready("Converter")->lineContactors.config.interlock == line_contactors_interlock::converter); + CHECK(ready("MotorBlowers")->lineContactors.config.interlock == line_contactors_interlock::motor_blowers); + CHECK(ready("Something")->lineContactors.config.interlock == line_contactors_interlock::none); } TEST_CASE("line contactors interlock: without one the converter and the blowers don't matter, as before") { auto locomotive{ready("")}; - locomotive->converter.running = false; + locomotive->converter.SetRunningForTest(false); for (auto &blower : locomotive->MotorBlowers) { blower.is_active = false; } @@ -51,12 +51,12 @@ TEST_CASE("line contactors interlock: without one the converter and the blowers TEST_CASE("line contactors interlock: on the converter, they close only with the vehicle's own converter running") { auto locomotive{ready("Converter")}; - locomotive->converter.running = false; + locomotive->converter.SetRunningForTest(false); locomotive->lowVoltage.power110vAvailable = true; // the 110 V from the other section doesn't run this one's fans CHECK_FALSE(locomotive->MotorConnectorsCheck()); - locomotive->converter.running = true; + locomotive->converter.SetRunningForTest(true); CHECK(locomotive->MotorConnectorsCheck()); - locomotive->lineBreaker.closed = false; // the other conditions still hold + locomotive->lineBreaker.Open(); // the other conditions still hold CHECK_FALSE(locomotive->MotorConnectorsCheck()); } @@ -124,10 +124,10 @@ bool blowers_run(physics::Vehicle const &Physics) { // the driver's first power position, held until the line contactors close (their delay, the pressure switch) bool close_line_contactors(test::driven const &Driven) { Driven.controlling.IncMainCtrl(1); - for (int i = 0; i < 30 && false == Driven.controlling.lineContactors.closed; ++i) { + for (int i = 0; i < 30 && false == Driven.controlling.lineContactors.IsClosed(); ++i) { test::drive(Driven, line, 1.0); } - return Driven.controlling.lineContactors.closed; + return Driven.controlling.lineContactors.IsClosed(); } // the brakes released and the cylinders empty enough for the pressure switch to let the vehicle start @@ -154,7 +154,7 @@ TEST_CASE("line contactors interlock: with blowers starting with the speed the v .set("Engine", "MotorBlowersSustainTime", 10.0), 0.0, "test", 1}; auto &physics{eu07.physics()}; - REQUIRE(physics.lineContactors.interlock == line_contactors_interlock::motor_blowers); + REQUIRE(physics.lineContactors.config.interlock == line_contactors_interlock::motor_blowers); REQUIRE(physics.MotorBlowers[VehicleEnd::front].min_start_velocity == doctest::Approx(5.0)); REQUIRE(physics.MotorBlowers[VehicleEnd::rear].sustain_time == doctest::Approx(10.0)); auto driven{test::driving(eu07)}; @@ -177,7 +177,7 @@ TEST_CASE("line contactors interlock: with blowers starting with the speed the v } REQUIRE(eu07.speed() >= 10.0); CHECK(blowers_run(physics)); - CHECK(physics.lineContactors.closed); + CHECK(physics.lineContactors.IsClosed()); // a stop longer than the blowers keep running for while (physics.DecMainCtrl(1)) { @@ -190,7 +190,7 @@ TEST_CASE("line contactors interlock: with blowers starting with the speed the v REQUIRE(std::abs(eu07.speed()) <= 0.1); test::drive(driven, line, 15.0); REQUIRE_FALSE(blowers_run(physics)); - REQUIRE_FALSE(physics.lineContactors.closed); + REQUIRE_FALSE(physics.lineContactors.IsClosed()); // and the vehicle starts again release(driven); @@ -223,7 +223,7 @@ TEST_CASE("line contactors interlock: a blower starting with the speed, switched // the switch of the rear blower: off, the contactors open and stay open, standing as well as later REQUIRE(physics.MotorBlowersSwitchOff(true, VehicleEnd::rear)); test::drive(driven, line, 2.0); - CHECK_FALSE(physics.lineContactors.closed); + CHECK_FALSE(physics.lineContactors.IsClosed()); CHECK(std::abs(physics.Im) < 0.5); while (physics.DecMainCtrl(1)) { // down to zero @@ -245,13 +245,13 @@ TEST_CASE("line contactors interlock: held by the local converter switch only wh // what the AI driver looks at to switch the converter of a section back on (TController, the converteron hint) auto interlocked{ready("Converter")}; CHECK_FALSE(interlocked->LineContactorsHeldByLocalConverterSwitch()); - interlocked->converter.allowLocal = false; + interlocked->converter.SetLocalSwitch(false); CHECK(interlocked->LineContactorsHeldByLocalConverterSwitch()); for (auto const *other : {"", "MotorBlowers"}) { CAPTURE(other); auto locomotive{ready(other)}; - locomotive->converter.allowLocal = false; + locomotive->converter.SetLocalSwitch(false); CHECK_FALSE(locomotive->LineContactorsHeldByLocalConverterSwitch()); } } @@ -264,13 +264,13 @@ TEST_CASE("line contactors interlock: the ET42 section with its fans switched of REQUIRE(test::start_up(driven, line)); auto &front{et42[0].physics()}; auto &rear{et42[1].physics()}; - REQUIRE(front.converter.running); - REQUIRE(rear.converter.running); + REQUIRE(front.converter.IsRunning()); + REQUIRE(rear.converter.IsRunning()); // the fans of the rear section switched off with its own switch, the 110 V of the front one still reaches it - rear.converter.allowLocal = false; + rear.converter.SetLocalSwitch(false); test::drive(driven, line, 2.0); - REQUIRE_FALSE(rear.converter.running); + REQUIRE_FALSE(rear.converter.IsRunning()); CHECK(rear.lowVoltage.power110vAvailable); test::release_brakes(driven.cab); @@ -280,23 +280,23 @@ TEST_CASE("line contactors interlock: the ET42 section with its fans switched of test::drive(driven, line, 20.0); driven.controlling.IncMainCtrl(1); // as the AI does, it waits at the first position for the contactors (their delay, the pressure switch) - for (int i = 0; i < 90 && false == front.lineContactors.closed; ++i) { + for (int i = 0; i < 90 && false == front.lineContactors.IsClosed(); ++i) { test::drive(driven, line, 1.0); } - CHECK(front.lineContactors.closed); - CHECK_FALSE(rear.lineContactors.closed); + CHECK(front.lineContactors.IsClosed()); + CHECK_FALSE(rear.lineContactors.IsClosed()); // the fans back on, the section starts too - rear.converter.allowLocal = true; + rear.converter.SetLocalSwitch(true); test::drive(driven, line, 10.0); - REQUIRE(rear.converter.running); - CHECK(rear.lineContactors.closed); + REQUIRE(rear.converter.IsRunning()); + CHECK(rear.lineContactors.IsClosed()); // and the fans switched off on the way open its line contactors again - rear.converter.allowLocal = false; + rear.converter.SetLocalSwitch(false); test::drive(driven, line, 2.0); - CHECK_FALSE(rear.lineContactors.closed); - CHECK(front.lineContactors.closed); + CHECK_FALSE(rear.lineContactors.IsClosed()); + CHECK(front.lineContactors.IsClosed()); } TEST_CASE("louvres: closed until the main reservoir reaches the pressure that opens them") { diff --git a/tests/unit/test_linebreaker.cpp b/tests/unit/test_linebreaker.cpp index d0a678c7d..55f637bf9 100644 --- a/tests/unit/test_linebreaker.cpp +++ b/tests/unit/test_linebreaker.cpp @@ -37,10 +37,10 @@ struct lever { } // TTrain::Update() void update() { - if (breaker == state::open && physics.lineBreaker.closed) { + if (breaker == state::open && physics.lineBreaker.IsClosed()) { breaker = state::closed; } - if (breaker == state::closed && false == physics.lineBreaker.closed) { + if (breaker == state::closed && false == physics.lineBreaker.IsClosed()) { breaker = state::open; } if (on && breaker == state::open && physics.MainSwitchCheck()) { @@ -71,16 +71,16 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r test::track const line{0.15, 0.0, test::catenary_3kv}; auto const driver{test::driving(train)}; REQUIRE(test::start_up(driver, line)); - REQUIRE(ep05.lineBreaker.closed); - REQUIRE(ep05.converter.running); + REQUIRE(ep05.lineBreaker.IsClosed()); + REQUIRE(ep05.converter.IsRunning()); 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 - ep05.converter.overloaded = true; + ep05.converter.Overload(); ep05.MainSwitch(false, range_t::local); ws.update(); - REQUIRE_FALSE(ep05.lineBreaker.closed); + REQUIRE_FALSE(ep05.lineBreaker.IsClosed()); REQUIRE(ws.breaker == state::open); CHECK(ws.on); // with the relay tripped the breaker doesn't close @@ -93,7 +93,7 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r ws.press(); CHECK(ws.on); ws.update(); - CHECK_FALSE(ep05.lineBreaker.closed); + CHECK_FALSE(ep05.lineBreaker.IsClosed()); ws.press(); CHECK_FALSE(ws.on); @@ -101,15 +101,15 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r ep05.ConverterSwitch(false, range_t::local); test::drive(driver, line, 1.0); CHECK(ep05.RelayReset(relay_t::primaryconverteroverload, range_t::local)); - CHECK_FALSE(ep05.converter.overloaded); + CHECK_FALSE(ep05.converter.IsOverloaded()); ws.update(); - CHECK_FALSE(ep05.lineBreaker.closed); // the lever is off + CHECK_FALSE(ep05.lineBreaker.IsClosed()); // the lever is off ws.press(); ws.update(); - CHECK(ep05.lineBreaker.closed); + CHECK(ep05.lineBreaker.IsClosed()); CHECK(ws.breaker == state::closed); // and the next press opens it ws.press(); CHECK_FALSE(ws.on); - CHECK_FALSE(ep05.lineBreaker.closed); + CHECK_FALSE(ep05.lineBreaker.IsClosed()); } diff --git a/tests/unit/test_mains_before_pantographs.cpp b/tests/unit/test_mains_before_pantographs.cpp index 11d8b889a..fdbd4ca91 100644 --- a/tests/unit/test_mains_before_pantographs.cpp +++ b/tests/unit/test_mains_before_pantographs.cpp @@ -69,7 +69,7 @@ void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const test::release_brakes(Driven.cab); test::drive(Driven, line, 20.0); // until the pressure switch lets the line contactors close - for (int i = 0; i < 120 && Loco->protection.pressureSwitch; ++i) { + for (int i = 0; i < 120 && Loco->protection.PressureSwitchTripped(); ++i) { test::drive(Driven, line, 1.0); } for (int i = 0; i < Position; ++i) { @@ -80,7 +80,7 @@ void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const REQUIRE(Loco->MainCtrlPos == Position); REQUIRE(Loco->MainCtrlActualPos == Position); REQUIRE(Loco->RList[Position].R > 0.0); // a resistance position - REQUIRE(Loco->lineContactors.closed); + REQUIRE(Loco->lineContactors.IsClosed()); REQUIRE(std::abs(Loco->Im) > 10.0); } @@ -88,29 +88,29 @@ void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const TEST_CASE("mains before pantographs: without the flag the line breaker needs the pantographs' voltage, as before") { test::vehicle loco{ep05(false), 0.0, "test", 1}; - REQUIRE_FALSE(loco->lineBreaker.pantographsRequireIt); + REQUIRE_FALSE(loco->lineBreaker.config.pantographsRequireIt); prepare(loco); close_line_breaker(loco); - CHECK_FALSE(loco->lineBreaker.closed); + CHECK_FALSE(loco->lineBreaker.IsClosed()); raise_pantograph(loco); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); close_line_breaker(loco); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); // the pantographs stay up with the line breaker open, and the line breaker opens without voltage loco->MainSwitch(false); loco.run(2.0, line); CHECK(loco->pantographs[VehicleEnd::rear].is_active); close_line_breaker(loco); - REQUIRE(loco->lineBreaker.closed); + REQUIRE(loco->lineBreaker.IsClosed()); loco->OperatePantographValve(VehicleEnd::rear, operation_t::disable); loco.run(2.0, line); - CHECK_FALSE(loco->lineBreaker.closed); + CHECK_FALSE(loco->lineBreaker.IsClosed()); } TEST_CASE("mains before pantographs: with the flag the pantographs rise only through the closed line breaker") { test::vehicle loco{ep05(true), 0.0, "test", 1}; - REQUIRE(loco->lineBreaker.pantographsRequireIt); + REQUIRE(loco->lineBreaker.config.pantographsRequireIt); prepare(loco); // the pantographs stay down while the line breaker is open raise_pantograph(loco); @@ -118,15 +118,15 @@ TEST_CASE("mains before pantographs: with the flag the pantographs rise only thr CHECK(loco->pantographCircuit.supplyVoltage == 0.0); // the line breaker closes without voltage, and the pantograph rises through it close_line_breaker(loco); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); raise_pantograph(loco); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); // opening the line breaker drops the pantograph, which stays down until the line breaker closes again loco->MainSwitch(false); loco.run(2.0, line); - CHECK_FALSE(loco->lineBreaker.closed); + CHECK_FALSE(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == 0.0); // a pantograph lowered under the closed line breaker leaves it closed @@ -136,7 +136,7 @@ TEST_CASE("mains before pantographs: with the flag the pantographs rise only thr loco->OperatePantographValve(VehicleEnd::rear, operation_t::disable); loco.run(5.0, line); CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); } TEST_CASE("mains before pantographs: with the flag the line breaker still needs the battery") { @@ -144,7 +144,7 @@ TEST_CASE("mains before pantographs: with the flag the line breaker still needs loco.hold_main_reservoir(6.0); loco.run(2.0, line); close_line_breaker(loco); - CHECK_FALSE(loco->lineBreaker.closed); + CHECK_FALSE(loco->lineBreaker.IsClosed()); } TEST_CASE("mains before pantographs: with the flag the driver's start-up gets the locomotive ready") { @@ -152,7 +152,7 @@ TEST_CASE("mains before pantographs: with the flag the driver's start-up gets th test::vehicle loco{ep05(true), 0.0, "test", 1}; auto driven{test::driving(loco)}; REQUIRE(test::start_up(driven, line)); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); CHECK(test::is_ready(driven)); } @@ -164,17 +164,17 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres test::vehicle loco{ep05(true), 0.0, "test", 1}; prepare(loco); close_line_breaker(loco); - REQUIRE(loco->lineBreaker.closed); + REQUIRE(loco->lineBreaker.IsClosed()); REQUIRE(loco->pantographCircuit.supplyVoltage == 0.0); switch_auxiliaries_on(loco); - REQUIRE(loco->converter.allow); + REQUIRE(loco->converter.IsAllowed()); REQUIRE(loco->air.compressor.allow); // the line breaker closed on the battery, the pantographs down: there's nothing to run them on CHECK(reservoir_gain(loco, 20.0, line) < 0.01); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->MainCircuitPowered()); - CHECK_FALSE(loco->converter.running); + CHECK_FALSE(loco->converter.IsRunning()); CHECK_FALSE(loco->lowVoltage.power110vAvailable); CHECK_FALSE(loco->air.compressor.running); @@ -183,7 +183,7 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); CHECK(reservoir_gain(loco, 10.0, line) > 0.1); CHECK(loco->MainCircuitPowered()); - CHECK(loco->converter.running); + CHECK(loco->converter.IsRunning()); CHECK(loco->lowVoltage.power110vAvailable); CHECK(loco->air.compressor.running); @@ -205,9 +205,9 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(weak.voltage)); } CHECK(reservoir_gain(loco, 10.0, *track) < 0.01); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->MainCircuitPowered()); - CHECK_FALSE(loco->converter.running); + CHECK_FALSE(loco->converter.IsRunning()); CHECK_FALSE(loco->lowVoltage.power110vAvailable); CHECK_FALSE(loco->air.compressor.running); } @@ -220,7 +220,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui REQUIRE(loco->HeatingPowerSource.SourceType == TPowerSource::Main); prepare(loco); close_line_breaker(loco); - REQUIRE(loco->lineBreaker.closed); + REQUIRE(loco->lineBreaker.IsClosed()); loco->CompressorSwitch(true); loco->MotorBlowersSwitch(true, VehicleEnd::front); loco->RVentForceOn = true; @@ -237,7 +237,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui raise_pantograph(loco, weak); REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(weak.voltage)); CHECK(reservoir_gain(loco, 10.0, weak) < 0.01); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->air.compressor.running); CHECK_FALSE(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot == 0.0); @@ -259,18 +259,18 @@ TEST_CASE("mains before pantographs: without the flag the converter and the comp prepare(loco); raise_pantograph(loco); close_line_breaker(loco); - REQUIRE(loco->lineBreaker.closed); + REQUIRE(loco->lineBreaker.IsClosed()); switch_auxiliaries_on(loco); CHECK(reservoir_gain(loco, 10.0, line) > 0.1); CHECK(loco->MainCircuitPowered()); - CHECK(loco->converter.running); + CHECK(loco->converter.IsRunning()); CHECK(loco->lowVoltage.power110vAvailable); CHECK(loco->air.compressor.running); // too low a voltage opens the line breaker, and they stop with it loco.run(5.0, weak); - CHECK_FALSE(loco->lineBreaker.closed); + CHECK_FALSE(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->MainCircuitPowered()); - CHECK_FALSE(loco->converter.running); + CHECK_FALSE(loco->converter.IsRunning()); CHECK_FALSE(loco->lowVoltage.power110vAvailable); CHECK_FALSE(loco->air.compressor.running); } @@ -287,10 +287,10 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when // the voltage goes: the line breaker holds, the pantograph stays up, the motors are cut off test::drive(driven, dead, 3.0); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); - CHECK_FALSE(loco->protection.noVoltage); - CHECK_FALSE(loco->lineContactors.closed); + CHECK_FALSE(loco->protection.UndervoltageHolds()); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->Im == 0.0); // the voltage back, with the master controller still where it was: the camshaft went down to zero and stays @@ -298,10 +298,10 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when test::drive(driven, line, 10.0); REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); REQUIRE(loco->MainCtrlPos == 5); - CHECK(loco->lineBreaker.closed); - CHECK(loco->converter.running); - CHECK_FALSE(loco->protection.noVoltage); - CHECK_FALSE(loco->lineContactors.closed); + CHECK(loco->lineBreaker.IsClosed()); + CHECK(loco->converter.IsRunning()); + CHECK_FALSE(loco->protection.UndervoltageHolds()); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->MainCtrlActualPos == 0); CHECK(loco->Im == 0.0); @@ -311,13 +311,13 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when } REQUIRE(loco->MainCtrlPos == 0); test::drive(driven, line, 1.0); - CHECK(loco->protection.noVoltage); - CHECK_FALSE(loco->lineContactors.closed); + CHECK(loco->protection.UndervoltageHolds()); + CHECK_FALSE(loco->lineContactors.IsClosed()); for (int i = 0; i < 3; ++i) { loco->IncMainCtrl(1); test::drive(driven, line, 2.0); } - CHECK(loco->lineContactors.closed); + CHECK(loco->lineContactors.IsClosed()); CHECK(loco->MainCtrlActualPos == 3); CHECK(std::abs(loco->Im) > 10.0); } @@ -327,8 +327,8 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when } REQUIRE(loco->MainCtrlPos == 1); test::drive(driven, line, 2.0); - CHECK(loco->protection.noVoltage); - CHECK(loco->lineContactors.closed); + CHECK(loco->protection.UndervoltageHolds()); + CHECK(loco->lineContactors.IsClosed()); CHECK(loco->MainCtrlActualPos == 1); } } @@ -339,13 +339,13 @@ TEST_CASE("mains before pantographs: without the flag the line breaker opens whe get_under_power(loco, driven, 5); test::drive(driven, dead, 3.0); - CHECK_FALSE(loco->lineBreaker.closed); - CHECK_FALSE(loco->lineContactors.closed); + CHECK_FALSE(loco->lineBreaker.IsClosed()); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->Im == 0.0); // and stays open with the voltage back test::drive(driven, line, 10.0); - CHECK_FALSE(loco->lineBreaker.closed); - CHECK_FALSE(loco->lineContactors.closed); + CHECK_FALSE(loco->lineBreaker.IsClosed()); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->MainCtrlActualPos == 0); CHECK(loco->Im == 0.0); } diff --git a/tests/unit/test_oil_pump.cpp b/tests/unit/test_oil_pump.cpp index 7d7acb902..94e590208 100644 --- a/tests/unit/test_oil_pump.cpp +++ b/tests/unit/test_oil_pump.cpp @@ -21,7 +21,7 @@ TEST_CASE("oil pump: the pre-lubrication pump works before the engine start and loco->OilPumpCheck(0.01); CHECK(loco->OilPump.is_active); - loco->lineBreaker.closed = true; // engine started + loco->lineBreaker.Close(); // engine started loco->OilPumpCheck(0.01); CHECK_FALSE(loco->OilPump.is_active); } @@ -39,7 +39,7 @@ TEST_CASE("oil pump: the pump started with the engine start procedure stops once loco->OilPumpCheck(0.01); CHECK(loco->OilPump.is_active); - loco->lineBreaker.closed = true; + loco->lineBreaker.Close(); loco->OilPumpCheck(0.01); CHECK_FALSE(loco->OilPump.is_active); } diff --git a/tests/unit/test_pressure_switch.cpp b/tests/unit/test_pressure_switch.cpp index 8645b5165..2c30692d6 100644 --- a/tests/unit/test_pressure_switch.cpp +++ b/tests/unit/test_pressure_switch.cpp @@ -45,11 +45,11 @@ 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->protection.pressureSwitch; ++i) { + for (int i = 0; i < 120 && Loco->protection.PressureSwitchTripped(); ++i) { test::drive(Driven, line, 1.0); } - REQUIRE_FALSE(Loco->protection.pressureSwitch); - REQUIRE(Loco->lineBreaker.closed); + REQUIRE_FALSE(Loco->protection.PressureSwitchTripped()); + REQUIRE(Loco->lineBreaker.IsClosed()); REQUIRE(Loco->pantographs[VehicleEnd::rear].is_active); } @@ -65,7 +65,7 @@ void notch_up(test::vehicle &Loco, test::driven const &Driven, int const Positio 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->lineContactors.closed); + REQUIRE(Loco->lineContactors.IsClosed()); REQUIRE(std::abs(Loco->Im) > 10.0); } @@ -87,14 +87,14 @@ void emergency_application(test::vehicle &Loco, test::driven const &Driven) { TEST_CASE("pressure switch: the keys are off by default") { test::vehicle loco{ep05({}), 0.0, "test", 1}; - CHECK(loco->protection.hasPressureSwitch); - CHECK(loco->protection.pressureSwitchWatchesCylinders); - CHECK(loco->lineBreaker.emergencyOffPressure == 0.0); + CHECK(loco->protection.config.hasPressureSwitch); + CHECK(loco->protection.config.pressureSwitchWatchesCylinders); + CHECK(loco->lineBreaker.config.emergencyOffPressure == 0.0); test::vehicle changed{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; - CHECK(changed->protection.hasPressureSwitch); - CHECK_FALSE(changed->protection.pressureSwitchWatchesCylinders); - CHECK(changed->lineBreaker.emergencyOffPressure == doctest::Approx(emergency_pressure)); + CHECK(changed->protection.config.hasPressureSwitch); + CHECK_FALSE(changed->protection.config.pressureSwitchWatchesCylinders); + CHECK(changed->lineBreaker.config.emergencyOffPressure == doctest::Approx(emergency_pressure)); } TEST_CASE("pressure switch: with the brake cylinders at 3.8 bar the EP05 takes no current, as before") { @@ -102,13 +102,13 @@ TEST_CASE("pressure switch: with the brake cylinders at 3.8 bar the EP05 takes n auto driven{test::driving(loco)}; get_ready(loco, driven); apply_independent_brake(loco, driven); - CHECK(loco->protection.pressureSwitch); + CHECK(loco->protection.PressureSwitchTripped()); CHECK_FALSE(loco->MainCircuitLampsEnabled()); notch_up(loco, driven, 3); - CHECK_FALSE(loco->lineContactors.closed); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->Im == 0.0); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); } @@ -117,13 +117,13 @@ TEST_CASE("pressure switch: without its brake cylinder half the EP05 takes curre auto driven{test::driving(loco)}; get_ready(loco, driven); apply_independent_brake(loco, driven); - CHECK_FALSE(loco->protection.pressureSwitch); + CHECK_FALSE(loco->protection.PressureSwitchTripped()); // 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->lineContactors.closed); + CHECK(loco->lineContactors.IsClosed()); CHECK(loco->MainCtrlActualPos == 3); CHECK(std::abs(loco->Im) > 100.0); CHECK(loco->brakes.cylinderPressure == doctest::Approx(3.8).epsilon(0.03)); @@ -144,11 +144,11 @@ TEST_CASE("pressure switch: without its brake cylinder half the brake pipe still SUBCASE("an emergency application") { emergency_application(loco, driven); } - CHECK(loco->protection.pressureSwitch); - CHECK_FALSE(loco->lineContactors.closed); + CHECK(loco->protection.PressureSwitchTripped()); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->Im == 0.0); // nothing else lets go without the other key - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); } @@ -166,17 +166,17 @@ TEST_CASE("pressure switch: an emergency application with the master controller test::drive(driven, line, 10.0); REQUIRE(loco->brakePipe.pressure < emergency_pressure); REQUIRE(loco->MainCtrlPos == 5); - CHECK_FALSE(loco->lineBreaker.closed); + CHECK_FALSE(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->pantographs[VehicleEnd::front].is_active); CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == 0.0); - CHECK_FALSE(loco->lineContactors.closed); + CHECK_FALSE(loco->lineContactors.IsClosed()); 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->lineBreaker.closed); + CHECK_FALSE(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); } @@ -191,7 +191,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller REQUIRE(loco->MainCtrlPos == 0); emergency_application(loco, driven); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); CHECK(loco->Im == 0.0); @@ -199,7 +199,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller // 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->lineBreaker.closed); + CHECK_FALSE(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); } @@ -218,10 +218,10 @@ TEST_CASE("pressure switch: a service application with the master controller on MESSAGE("the lowest brake pipe pressure of the service application: " << lowest << " bar"); REQUIRE(lowest < 3.0); CHECK(lowest > emergency_pressure); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); // the pressure switch has cut the motors off - CHECK_FALSE(loco->lineContactors.closed); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->Im == 0.0); } @@ -232,26 +232,26 @@ TEST_CASE("pressure switch: without the key an emergency application leaves the emergency_application(loco, driven); REQUIRE(loco->MainCtrlPos == 5); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); // the pressure switch cuts the motors off - CHECK(loco->protection.pressureSwitch); - CHECK_FALSE(loco->lineContactors.closed); + CHECK(loco->protection.PressureSwitchTripped()); + CHECK_FALSE(loco->lineContactors.IsClosed()); 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->lineBreaker.pantographsRequireIt); + REQUIRE_FALSE(loco->lineBreaker.config.pantographsRequireIt); auto driven{test::driving(loco)}; get_under_power(loco, driven, 5); emergency_application(loco, driven); - CHECK_FALSE(loco->lineBreaker.closed); + CHECK_FALSE(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); - CHECK_FALSE(loco->lineContactors.closed); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->Im == 0.0); } @@ -263,33 +263,33 @@ TEST_CASE("pressure switch: after the emergency application the driver's start-u auto driven{test::driving(loco)}; get_under_power(loco, driven, 5); emergency_application(loco, driven); - REQUIRE_FALSE(loco->lineBreaker.closed); + REQUIRE_FALSE(loco->lineBreaker.IsClosed()); REQUIRE_FALSE(loco->pantographs[VehicleEnd::rear].is_active); REQUIRE(loco->pantographs[VehicleEnd::rear].valve.is_enabled); // with the brake pipe still empty REQUIRE(test::start_up(driven, line, 60.0)); CHECK(loco->MainCtrlPos == 0); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); REQUIRE(loco->brakePipe.pressure < emergency_pressure); // and it stays so test::drive(driven, line, 30.0); - CHECK(loco->lineBreaker.closed); + CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::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->protection.pressureSwitch; ++i) { + for (int i = 0; i < 180 && loco->protection.PressureSwitchTripped(); ++i) { loco->BrakeReleaser(loco->brakePipe.pressure < 3.0 ? 1 : 0); test::drive(driven, line, 1.0); } loco->BrakeReleaser(0); - REQUIRE_FALSE(loco->protection.pressureSwitch); + REQUIRE_FALSE(loco->protection.PressureSwitchTripped()); notch_up(loco, driven, 3); - CHECK(loco->lineBreaker.closed); - CHECK(loco->lineContactors.closed); + CHECK(loco->lineBreaker.IsClosed()); + CHECK(loco->lineContactors.IsClosed()); CHECK(std::abs(loco->Im) > 10.0); } diff --git a/tests/unit/test_smoke.cpp b/tests/unit/test_smoke.cpp index 5ee3a75f3..2ff88b209 100644 --- a/tests/unit/test_smoke.cpp +++ b/tests/unit/test_smoke.cpp @@ -102,10 +102,10 @@ namespace { // the locomotive's engine started the way the AI starts it, a second at a time, until it runs (Mains) bool start_engine(test::driven const &Driven, test::track const &Track) { - for (int second = 0; second < 120 && false == Driven.controlling.lineBreaker.closed; ++second) { + for (int second = 0; second < 120 && false == Driven.controlling.lineBreaker.IsClosed(); ++second) { test::start_up(Driven, Track, 1.0); } - return Driven.controlling.lineBreaker.closed; + return Driven.controlling.lineBreaker.IsClosed(); } } // namespace @@ -126,7 +126,7 @@ TEST_CASE("smoke: a real diesel smokes only once its engine has fired, SmokeDela CHECK(smoke::vehicle_spawn_count(locomotive.physics(), true, source, update) == 0.f); // it has fired since test::drive(driven, track, 3.0); - CHECK(locomotive->lineBreaker.closed); + CHECK(locomotive->lineBreaker.IsClosed()); CHECK(locomotive->diesel.firingCountdown == 0.0); CHECK(smoke::vehicle_spawn_count(locomotive.physics(), true, source, update) >= 1.f); } diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp index 41047924b..d8ed80dcd 100644 --- a/tests/unit/test_speed_control.cpp +++ b/tests/unit/test_speed_control.cpp @@ -57,7 +57,7 @@ void get_6dg_going(scenario &Scenario) { Scenario.wait(1.0); move_to(loco, dg_hold); Scenario.wait(5.0); - REQUIRE(loco.lineContactors.closed); + REQUIRE(loco.lineContactors.IsClosed()); } } // namespace @@ -309,7 +309,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the 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.lineContactors.closed); + CHECK(loco.lineContactors.IsClosed()); CHECK(shunted > 0); CHECK(unshunted > 0); CHECK_FALSE(loco.IncScndCtrl(1)); // still not the driver's @@ -321,13 +321,13 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the // 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.lineContactors.closed); + CHECK_FALSE(loco.lineContactors.IsClosed()); 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.lineContactors.closed); + CHECK(loco.lineContactors.IsClosed()); CHECK(loco.Vel == doctest::Approx(30.0).epsilon(0.05)); CHECK(loco.ScndCtrlPos == 0); // out at this speed @@ -356,7 +356,7 @@ TEST_CASE("speed control apart: the ST45's cruise control on its own switch, wit CHECK(loco.SpeedCtrlValue == doctest::Approx(60.0)); scenario.wait(90.0); CHECK(loco.Vel == doctest::Approx(60.0).epsilon(0.03)); - CHECK(loco.lineContactors.closed); + CHECK(loco.lineContactors.IsClosed()); scenario.act("step up, power down"); loco.SpeedCtrlInc(); CHECK(loco.SpeedCtrlValue == doctest::Approx(65.0)); diff --git a/tests/unit/test_traction.cpp b/tests/unit/test_traction.cpp index 4b27a94a6..ec049c382 100644 --- a/tests/unit/test_traction.cpp +++ b/tests/unit/test_traction.cpp @@ -33,7 +33,7 @@ TEST_CASE("traction: every real powered vehicle started up, driven to full power test::drive_cycle(test::driving(real), test::track{0.15, 0.0, test::catenary_3kv}, trace); // every vehicle getting its line breaker closed runs off and is braked to a stop. the SM31 and the TEM2 // barely move (COVERAGE.md); the cars of a unit taking their power from another car don't start alone - if (real->lineBreaker.closed) { + if (real->lineBreaker.IsClosed()) { auto const crawls{path == "sm31_v1/411d" || path == "tem2_v2/tem2a"}; CHECK((real->DistCounter > 0.2 /* km */) != crawls); // but the road vehicle, which a minute of full service only slows down @@ -72,11 +72,11 @@ TEST_CASE("traction: the line breaker opened by the catenary lost, and by too hi scenario.get_going(); auto &controlling{scenario.driver().controlling}; scenario.full_power(10.0); - REQUIRE(controlling.lineBreaker.closed); + REQUIRE(controlling.lineBreaker.IsClosed()); scenario.act("catenary lost"); scenario.line().voltage = 0.0; scenario.wait(5.0); - CHECK_FALSE(controlling.lineBreaker.closed); + CHECK_FALSE(controlling.lineBreaker.IsClosed()); CHECK(controlling.Im == doctest::Approx(0.0)); scenario.act("catenary back"); scenario.line().voltage = test::catenary_3kv; @@ -86,7 +86,7 @@ TEST_CASE("traction: the line breaker opened by the catenary lost, and by too hi scenario.act("overvoltage"); scenario.line().voltage = controlling.EnginePowerSource.CollectorParameters.MaxV + 300.0; scenario.wait(5.0); - CHECK(controlling.lineBreaker.closed == (controlling.EngineType == TEngineType::ElectricSeriesMotor && false == controlling.EnginePowerSource.CollectorParameters.OVP)); + CHECK(controlling.lineBreaker.IsClosed() == (controlling.EngineType == TEngineType::ElectricSeriesMotor && false == controlling.EnginePowerSource.CollectorParameters.OVP)); scenario.line().voltage = test::catenary_3kv; stop(scenario); scenario.check(); diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index 64e2d1a6a..2ced8b5f1 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -823,17 +823,17 @@ TController::determine_consist_state() { [this, &islocalconverterswitchoff]( TDynamicObject * Vehicle ) { auto const *vehicle { Vehicle->physics }; islocalconverterswitchoff |= vehicle->LineContactorsHeldByLocalConverterSwitch(); - IsAnyConverterOverloadRelayOpen |= vehicle->converter.overloaded; + IsAnyConverterOverloadRelayOpen |= vehicle->converter.IsOverloaded(); IsAnyMotorOverloadRelayOpen |= vehicle->FuseFlag; - IsAnyGroundRelayOpen |= !vehicle->protection.ground; + IsAnyGroundRelayOpen |= !vehicle->protection.GroundHolds(); IsAnyCompressorPresent |= vehicle->air.compressor.speed > 0.0; IsAnyCompressorEnabled |= vehicle->air.compressor.speed > 0.0 ? (vehicle->air.compressor.allow || vehicle->air.compressor.start == start_t::automatic) && vehicle->air.compressor.allowLocal : false; IsAnyCompressorExplicitlyEnabled |= vehicle->air.compressor.speed > 0.0 ? vehicle->air.compressor.allow && vehicle->air.compressor.allowLocal : false; - IsAnyConverterPresent |= vehicle->converter.start != start_t::disabled; - IsAnyConverterEnabled |= ( vehicle->converter.allow || vehicle->converter.start == start_t::automatic ) && vehicle->converter.allowLocal; - IsAnyConverterExplicitlyEnabled |= vehicle->converter.allow && vehicle->converter.allowLocal; + IsAnyConverterPresent |= vehicle->converter.config.start != start_t::disabled; + IsAnyConverterEnabled |= ( vehicle->converter.IsAllowed() || vehicle->converter.config.start == start_t::automatic ) && vehicle->converter.LocalSwitchOn(); + IsAnyConverterExplicitlyEnabled |= vehicle->converter.IsAllowed() && vehicle->converter.LocalSwitchOn(); if( vehicle->Power > 0.01 ) { - IsAnyLineBreakerOpen |= !vehicle->lineBreaker.closed; } } ); + IsAnyLineBreakerOpen |= !vehicle->lineBreaker.IsClosed(); } } ); // siłę generują pojazdy na pochyleniu ale działa ona całość składu, więc a=F/m fAccGravity *= iDirection >= 0 ? 1 : -1; @@ -950,7 +950,7 @@ TController::determine_consist_state() { if( has_diesel_engine() ) { Ready = vehicle->Vel > EU07_AI_MOVEMENT // already moving - || false == vehicle->lineBreaker.closed // deadweight vehicle + || false == vehicle->lineBreaker.IsClosed() // deadweight vehicle || vehicle->enrot > 0.8 * (vehicle->EngineType == TEngineType::DieselEngine ? vehicle->diesel.minRevolutions : vehicle->DElist[0].RPM / 60.0); } p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła) diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index 37e7d314e..58b77d265 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -508,7 +508,7 @@ bool TController::IncSpeed() if( mvControlling->EnginePowerSource.SourceType == TPowerSource::Accumulator ) { fVoltage = mvControlling->lowVoltage.batteryVoltage; } - if (!IsAnyMotorOverloadRelayOpen && !mvControlling->protection.pressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->lineContactors.closed) && (Ready || drivingFlags.press)) { + if (!IsAnyMotorOverloadRelayOpen && !mvControlling->protection.PressureSwitchTripped() && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->lineContactors.IsClosed()) && (Ready || drivingFlags.press)) { // youBy polecił dodać 2012-09-08 v367 // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) auto const usehighoverloadrelaythreshold{mvControlling->TrainType != train_type::et42 // ET42 uses these variables for different purpose. TODO: fix this @@ -536,7 +536,7 @@ bool TController::IncSpeed() occupied->Vel <= (IsCargoTrain ? 40 : 30) + (seriesmodefieldshunting ? 5 : 0) - (fAccGravity < -0.025 ? 10 : 0)); // when not in series mode use the first available parallel mode configuration until 50/60 km/h for passenger/cargo train // (if there's only one parallel mode configuration it'll be used regardless of current speed) - auto const usefieldshunting = mvControlling->lineContactors.closed && mvControlling->RList[mvControlling->MainCtrlPos].R < 0.01 && false == mvControlling->IsScndCtrlLockedByMainCtrl() && + auto const usefieldshunting = mvControlling->lineContactors.IsClosed() && mvControlling->RList[mvControlling->MainCtrlPos].R < 0.01 && false == mvControlling->IsScndCtrlLockedByMainCtrl() && (useseriesmode ? mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1 : true == sufficientacceleration && true == sufficienttractionforce && occupied->Vel <= (IsCargoTrain ? 60 : 50) + (parallelmodefieldshunting ? 5 : 0) ? mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 : @@ -607,7 +607,7 @@ bool TController::IncSpeed() OK = sufficientpowermargin && false == mvControlling->DelayCtrlFlag ? mvControlling->IncMainCtrl(1) : true; // czekaj na 1 pozycji, zanim się nie włączą liniowe - if (true == mvControlling->lineContactors.closed) + if (true == mvControlling->lineContactors.IsClosed()) { drivingFlags.incSpeed = true; } @@ -643,7 +643,7 @@ bool TController::IncSpeed() } break; case TEngineType::DieselElectric: - if (!IsAnyMotorOverloadRelayOpen && !mvControlling->protection.pressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->lineContactors.closed) && (Ready || drivingFlags.press)) { + if (!IsAnyMotorOverloadRelayOpen && !mvControlling->protection.PressureSwitchTripped() && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->lineContactors.IsClosed()) && (Ready || drivingFlags.press)) { // youBy polecił dodać 2012-09-08 v367 // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) //{(BrakePress<=0.01*MaxBrakePress)} @@ -658,7 +658,7 @@ bool TController::IncSpeed() if( !IsAnyMotorOverloadRelayOpen && (Ready || drivingFlags.press || occupied->ShuntMode) ) { //{(BrakePress<=0.01*MaxBrakePress)} OK = IncSpeedEIM(); - if (mvControlling->SpeedCtrl && mvControlling->lineBreaker.closed) + if (mvControlling->SpeedCtrl && mvControlling->lineBreaker.IsClosed()) { // cruise control auto const couplinginprogress{true == drivingFlags.connect && true == OrderCurrentGet().HasAll(DriverOrder::connect)}; @@ -689,7 +689,7 @@ bool TController::IncSpeed() { // dla 2Ls150 można zmienić tryb pracy, jeśli jest w liniowym i nie daje rady (wymaga zerowania kierunku) // mvControlling->ShuntMode=(OrderList[OrderPos]&Shunt)||(fMass>224000.0); } - if (mvControlling->SpeedCtrl && mvControlling->lineBreaker.closed) {// cruise control + if (mvControlling->SpeedCtrl && mvControlling->lineBreaker.IsClosed()) {// cruise control auto const couplinginprogress { true == drivingFlags.connect && true == OrderCurrentGet().HasAll(DriverOrder::connect) }; auto const SpeedCntrlVel { ( ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? @@ -725,7 +725,7 @@ bool TController::IncSpeed() } } // TODO: move this check to a more suitable place, or scrap it - if( false == mvControlling->lineBreaker.closed ) { + if( false == mvControlling->lineBreaker.IsClosed() ) { SpeedCntrl(0.0); mvControlling->DecScndCtrl( 2 ); cue_action( driver_hint::linebreakerclose ); @@ -935,7 +935,7 @@ void TController::SpeedSet() { } if( mvControlling->MainCtrlPos > 0 - && false == mvControlling->lineContactors.closed ) { + && false == mvControlling->lineContactors.IsClosed() ) { // jak niby jedzie, ale ma rozłączone liniowe to na zero i czekać na przewalenie kułakowego mvControlling->DecMainCtrl( 2 ); } @@ -1278,7 +1278,7 @@ void TController::SetTimeControllers() } } // 5.5 universal control for diesel electric vehicles - if (mvControlling->EngineType == TEngineType::DieselElectric && mvControlling->EIMCtrlType == 3 && AccDesired >= 0.0 && mvControlling->lineContactors.closed) + if (mvControlling->EngineType == TEngineType::DieselElectric && mvControlling->EIMCtrlType == 3 && AccDesired >= 0.0 && mvControlling->lineContactors.IsClosed()) { // NOTE: partial implementation for speedinc/dec // TBD, TODO: implement fully? diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index 661a3d7a8..b70f23289 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -86,7 +86,7 @@ bool TController::PrepareEngine() } } - if( mvControlling->lineBreaker.pantographsRequireIt + if( mvControlling->lineBreaker.config.pantographsRequireIt && IsAnyLineBreakerOpen ) { // the pantographs rise only through the closed line breaker, which closes without their voltage PrepareDirection(); @@ -307,7 +307,7 @@ bool TController::ReleaseEngine() { cue_action( driver_hint::frontpantographvalveoff ); cue_action( driver_hint::rearpantographvalveoff ); - if( false == mvControlling->lineBreaker.closed ) { + if( false == mvControlling->lineBreaker.IsClosed() ) { // finish vehicle shutdown if( has_diesel_engine() ) { // heating/cooling subsystem @@ -338,7 +338,7 @@ bool TController::ReleaseEngine() { occupied->DirActive == 0 // && ( false == IsAnyCompressorEnabled ) // && ( false == IsAnyConverterEnabled ) - && false == mvControlling->lineBreaker.closed + && false == mvControlling->lineBreaker.IsClosed() && false == occupied->lowVoltage.power24vAvailable }; if (OK) { diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index a6c7fbd78..af896e558 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -403,7 +403,7 @@ TController::control_handles() { switch( mvControlling->EngineType ) { case TEngineType::ElectricSeriesMotor: { // styczniki liniowe rozłączone yBARC - if( false == mvControlling->lineContactors.closed + if( false == mvControlling->lineContactors.IsClosed() && false == mvControlling->DelayCtrlFlag && mvControlling->MainCtrlPowerPos() > 1 ) { cue_action( driver_hint::mastercontrollersetzerospeed ); @@ -427,7 +427,7 @@ TController::control_handles() { } case TEngineType::DieselElectric: { // styczniki liniowe rozłączone yBARC - if( false == mvControlling->lineContactors.closed + if( false == mvControlling->lineContactors.IsClosed() && false == mvControlling->DelayCtrlFlag && mvControlling->MainCtrlPowerPos() > 1 ) { cue_action( driver_hint::mastercontrollersetzerospeed ); diff --git a/vehicle/cab/auxiliarycommands.cpp b/vehicle/cab/auxiliarycommands.cpp index 9bd043955..b2c8b50d3 100644 --- a/vehicle/cab/auxiliarycommands.cpp +++ b/vehicle/cab/auxiliarycommands.cpp @@ -682,9 +682,9 @@ void TTrain::OnCommand_convertertoggle(TTrain *Train, command_data const &Comman if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const overloadrelayisopen{(Train->Dynamic()->Mechanik != nullptr ? Train->Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : Train->occupied->converter.overloaded)}; + auto const overloadrelayisopen{(Train->Dynamic()->Mechanik != nullptr ? Train->Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : Train->occupied->converter.IsOverloaded())}; - if (Train->occupied->converter.switchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->occupied->lowVoltage.power110vAvailable && false == overloadrelayisopen) + if (Train->occupied->converter.config.switchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->occupied->lowVoltage.power110vAvailable && false == overloadrelayisopen) { // turn on OnCommand_converterenable(Train, Command); @@ -698,7 +698,7 @@ void TTrain::OnCommand_convertertoggle(TTrain *Train, command_data const &Comman else if (Command.action == GLFW_RELEASE) { // on button release... - if (Train->occupied->converter.switchType == "impulse") + if (Train->occupied->converter.config.switchType == "impulse") { // ...return switches to start position if applicable Train->ggConverterButton.UpdateValue(0.0, Train->dsbSwitch); @@ -717,7 +717,7 @@ void TTrain::OnCommand_converterenable(TTrain *Train, command_data const &Comman // impulse type switch has no effect if there's no power // NOTE: this is most likely setup wrong, but the whole thing is smoke and mirrors anyway - if (Train->occupied->converter.switchType != "impulse" || Train->controlled->lineBreaker.closed) + if (Train->occupied->converter.config.switchType != "impulse" || Train->controlled->lineBreaker.IsClosed()) { // won't start if the line breaker button is still held Train->occupied->ConverterSwitch(true); @@ -754,7 +754,7 @@ void TTrain::OnCommand_converterdisable(TTrain *Train, command_data const &Comma void TTrain::OnCommand_convertertogglelocal(TTrain *Train, command_data const &Command) { - if (Train->occupied->converter.start == start_t::automatic) + if (Train->occupied->converter.config.start == start_t::automatic) { // let the automatic thing do its automatic thing... return; @@ -767,13 +767,13 @@ void TTrain::OnCommand_convertertogglelocal(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->occupied->converter.allowLocal && Train->ggConverterLocalButton.GetValue() < 0.5) + if (false == Train->occupied->converter.LocalSwitchOn() && Train->ggConverterLocalButton.GetValue() < 0.5) { // turn on // visual feedback Train->ggConverterLocalButton.UpdateValue(1.0, Train->dsbSwitch); // effect - Train->occupied->converter.allowLocal = true; + Train->occupied->converter.SetLocalSwitch(true); /* if( true == Train->controlled->ConverterSwitch( true, range::local ) ) { // side effects @@ -791,7 +791,7 @@ void TTrain::OnCommand_convertertogglelocal(TTrain *Train, command_data const &C // visual feedback Train->ggConverterLocalButton.UpdateValue(0.0, Train->dsbSwitch); // effect - Train->occupied->converter.allowLocal = false; + Train->occupied->converter.SetLocalSwitch(false); /* if( true == Train->controlled->ConverterSwitch( false, range::local ) ) { // side effects diff --git a/vehicle/cab/powercommands.cpp b/vehicle/cab/powercommands.cpp index f9d17ecf7..a48f1dc66 100644 --- a/vehicle/cab/powercommands.cpp +++ b/vehicle/cab/powercommands.cpp @@ -403,13 +403,13 @@ void TTrain::OnCommand_motorconnectorsopen(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { // button works while it's held down but we can ignore repeats - if (false == Train->controlled->lineContactors.forcedOpen) + if (false == Train->controlled->lineContactors.IsForcedOpen()) { // open the connectors // visual feedback Train->ggStLinOffButton.UpdateValue(1.0, Train->dsbSwitch); - Train->controlled->lineContactors.forcedOpen = true; + Train->controlled->lineContactors.ForceOpen(true); Train->set_paired_open_motor_connectors_button(true); } else @@ -421,13 +421,13 @@ void TTrain::OnCommand_motorconnectorsopen(TTrain *Train, command_data const &Co else if (Command.action == GLFW_RELEASE) { // button released - if (Train->controlled->lineContactors.switchType != "toggle") + if (Train->controlled->lineContactors.config.switchType != "toggle") { // default button type (impulse) ceases its work on button release // visual feedback Train->ggStLinOffButton.UpdateValue(0.0, Train->dsbSwitch); - Train->controlled->lineContactors.forcedOpen = false; + Train->controlled->lineContactors.ForceOpen(false); Train->set_paired_open_motor_connectors_button(false); } } @@ -448,19 +448,19 @@ void TTrain::OnCommand_motorconnectorsclose(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { - if (Train->controlled->lineContactors.switchType == "toggle") + if (Train->controlled->lineContactors.config.switchType == "toggle") { // default type of button (impulse) has only one effect on press, but the toggle type can toggle the state // visual feedback Train->ggStLinOffButton.UpdateValue(0.0, Train->dsbSwitch); } - if (false == Train->controlled->lineContactors.forcedOpen) + if (false == Train->controlled->lineContactors.IsForcedOpen()) { return; } // already closed - Train->controlled->lineContactors.forcedOpen = false; + Train->controlled->lineContactors.ForceOpen(false); Train->set_paired_open_motor_connectors_button(false); } } diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index fe23cc0fe..47cc28267 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -930,7 +930,7 @@ void TTrain::set_cab_controls(int const Cab) } // motor connectors - ggStLinOffButton.PutValue(controlled->lineContactors.forcedOpen ? 1.f : 0.f); + ggStLinOffButton.PutValue(controlled->lineContactors.IsForcedOpen() ? 1.f : 0.f); // radio ggRadioChannelSelector.PutValue(static_cast((Dynamic()->Mechanik ? Dynamic()->Mechanik->iRadioChannel : 1) - 1)); // pantographs @@ -989,11 +989,11 @@ void TTrain::set_cab_controls(int const Cab) 1.f); ggPantCompressorButton.PutValue(pantographUnit->pantographAir.compressorRunning ? 1.f : 0.f); // converter - if (occupied->converter.switchType != "impulse") + if (occupied->converter.config.switchType != "impulse") { - ggConverterButton.PutValue(occupied->converter.allow ? 1.f : 0.f); + ggConverterButton.PutValue(occupied->converter.IsAllowed() ? 1.f : 0.f); } - ggConverterLocalButton.PutValue(occupied->converter.allowLocal ? 1.f : 0.f); + ggConverterLocalButton.PutValue(occupied->converter.LocalSwitchOn() ? 1.f : 0.f); // compressor ggCompressorButton.PutValue(controlled->air.compressor.allow ? 1.f : 0.f); ggCompressorLocalButton.PutValue(controlled->air.compressor.allowLocal ? 1.f : 0.f); diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 99987edb7..c9581e0d2 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -174,11 +174,11 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("master", occupied->CabMaster); // basic systems state data dict->insert("battery", occupied->lowVoltage.power24vAvailable); - dict->insert("linebreaker", controlled->lineBreaker.closed); - dict->insert("main_init", controlled->lineBreaker.initCountdown < controlled->lineBreaker.initTime && controlled->lineBreaker.initCountdown > 0.0); - dict->insert("main_ready", false == controlled->lineBreaker.closed && fHVoltage > 0.0 && controlled->lineBreaker.initCountdown <= 0.0); + dict->insert("linebreaker", controlled->lineBreaker.IsClosed()); + dict->insert("main_init", controlled->lineBreaker.RemainingInitTime() < controlled->lineBreaker.config.initTime && controlled->lineBreaker.RemainingInitTime() > 0.0); + dict->insert("main_ready", false == controlled->lineBreaker.IsClosed() && fHVoltage > 0.0 && controlled->lineBreaker.IsInitialised()); dict->insert("converter", occupied->lowVoltage.power110vAvailable); - dict->insert("converter_overload", controlled->converter.overloaded); + dict->insert("converter_overload", controlled->converter.IsOverloaded()); dict->insert("compress", controlled->air.compressor.running); dict->insert("pant_compressor", pantographUnit->pantographAir.compressorRunning); dict->insert("lights_front", occupied->iLights[VehicleEnd::front]); @@ -521,11 +521,11 @@ void TTrain::set_paired_open_motor_connectors_button(bool const State) // TODO: rework it into part of standard command propagation system if (controlled->Couplers[VehicleEnd::front].Connected != nullptr && true == controlled->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::permanent)) { - controlled->Couplers[VehicleEnd::front].Connected->lineContactors.forcedOpen = State; + controlled->Couplers[VehicleEnd::front].Connected->lineContactors.ForceOpen(State); } if (controlled->Couplers[VehicleEnd::rear].Connected != nullptr && true == controlled->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::permanent)) { - controlled->Couplers[VehicleEnd::rear].Connected->lineContactors.forcedOpen = State; + controlled->Couplers[VehicleEnd::rear].Connected->lineContactors.ForceOpen(State); } } } diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 8a56054b5..86e2281ee 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -140,12 +140,12 @@ bool TTrain::Update(double const Deltatime) void TTrain::updateLineBreakerState(double const Deltatime) { // line breaker: - if (m_linebreakerstate == linebreaker::state::open && true == controlled->lineBreaker.closed) + if (m_linebreakerstate == linebreaker::state::open && true == controlled->lineBreaker.IsClosed()) { // crude way to sync state of the linebreaker with ai-issued commands m_linebreakerstate = linebreaker::state::closed; } - if (m_linebreakerstate == linebreaker::state::closed && false == (controlled->lineBreaker.closed || controlled->diesel.startupRequested)) + if (m_linebreakerstate == linebreaker::state::closed && false == (controlled->lineBreaker.IsClosed() || controlled->diesel.startupRequested)) { // 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 @@ -153,7 +153,7 @@ void TTrain::updateLineBreakerState(double const Deltatime) } if (vehicle_cab::is_hold_coil_lever(ggMainOffButton) && hold_coil_lever::cuts_off(ggMainOffButton.GetDesiredValue())) { - if (true == controlled->lineBreaker.closed) + if (true == controlled->lineBreaker.IsClosed()) { // the line breaker was closed with the hold coil lever off, by the AI or through the control cable: // put the lever back on to match, like the line breaker state above @@ -482,11 +482,11 @@ void TTrain::updateUnitStates() fEIMParams[1 + in][8] = static_cast(p->physics->Itot); // p->physics->inductionMotor.state.lineCurrent; fEIMParams[1 + in][9] = static_cast(p->physics->EngineVoltage); fEIMParams[0][6] += fEIMParams[1 + in][8]; - bMains[in] = p->physics->lineBreaker.closed; + bMains[in] = p->physics->lineBreaker.IsClosed(); fCntVol[in] = static_cast(p->physics->lowVoltage.batteryVoltage); bFuse[in] = p->physics->FuseFlag; bBatt[in] = p->physics->lowVoltage.batteryOn; - bConv[in] = p->physics->converter.running; + bConv[in] = p->physics->converter.IsRunning(); bHeat[in] = p->physics->trainHeating.on; // bComp[in][2] = (p->physics->CompressorAllow || (p->physics->CompressorStart == start_t::automatic)); // bComp[in][3] = (p->physics->CompressorFlag); @@ -505,11 +505,11 @@ void TTrain::updateUnitStates() fDieselParams[1 + in][7] = p->physics->OilPump.pressure; fDieselParams[1 + in][8] = p->physics->diesel.heat.Ts; fDieselParams[1 + in][9] = static_cast(p->physics->retarder.fill); - bMains[in] = p->physics->lineBreaker.closed; + bMains[in] = p->physics->lineBreaker.IsClosed(); fCntVol[in] = static_cast(p->physics->lowVoltage.batteryVoltage); bFuse[in] = p->physics->FuseFlag; bBatt[in] = p->physics->lowVoltage.batteryOn; - bConv[in] = p->physics->converter.running; + bConv[in] = p->physics->converter.IsRunning(); bHeat[in] = p->physics->trainHeating.on; in++; iPowerNo = in; @@ -604,7 +604,7 @@ void TTrain::updateConverterOverload(double const Deltatime) //------------------ // hunter-261211: nadmiarowy przetwornicy i ogrzewania // Ra 15-01: to musi stąd wylecieć - zależności nie mogą być w kabinie - if (controlled->converter.running == true) + if (controlled->converter.IsRunning() == true) { fConverterTimer += static_cast(Deltatime); if (controlled->air.compressor.running == true && controlled->air.compressor.supply == physics::CompressorSupply::converterManual && (controlled->EngineType == TEngineType::ElectricSeriesMotor || controlled->TrainType == train_type::emu) && @@ -613,7 +613,7 @@ void TTrain::updateConverterOverload(double const Deltatime) { // hunter-091012: poprawka (zmiana warunku z CompressorPower /rozne od 0/ na /rowne 1/) if (fConverterTimer < fConverterPrzekaznik) { - controlled->converter.overloaded = true; + controlled->converter.Overload(); if (controlled->TrainType != train_type::emu) controlled->MainSwitch(false, controlled->TrainType == train_type::emu ? range_t::unit : range_t::local); } @@ -742,7 +742,7 @@ void TTrain::updateEngineGauges() fEngine[3] = static_cast(controlled->ShowEngineRotation(3)); if (ggMainGearStatus.SubModel) { - if (controlled->lineBreaker.closed) + if (controlled->lineBreaker.IsClosed()) ggMainGearStatus.UpdateValue(static_cast(1.1 - std::abs(controlled->diesel.automaticGearShift))); else ggMainGearStatus.UpdateValue(0.0); @@ -750,7 +750,7 @@ void TTrain::updateEngineGauges() } if (ggIgnitionKey.SubModel && ggIgnitionKey.GetDesiredValue() == 0.0) { - ggIgnitionKey.UpdateValue(controlled->lineBreaker.closed || controlled->diesel.startupRequested || fMainRelayTimer > 0.f || + ggIgnitionKey.UpdateValue(controlled->lineBreaker.IsClosed() || controlled->diesel.startupRequested || fMainRelayTimer > 0.f || (ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) || (ggMainOnButton.SubModel != nullptr && ggMainOnButton.GetDesiredValue() > 0.95)); } @@ -826,20 +826,20 @@ void TTrain::updateCircuitLamps(double const Deltatime) btLampkaSHP.Turn(occupied->SecuritySystem.is_cabsignal_blinking()); btLampkaCzuwakaSHP.Turn(btLampkaSHP.GetValue() || btLampkaCzuwaka.GetValue()); - btLampkaWylSzybki.Turn(m_linebreakerstate == linebreaker::state::closing || controlled->lineBreaker.closed); - btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !controlled->lineBreaker.closed); - btLampkaMainBreakerReady.Turn(controlled->lineBreaker.initCountdown <= 0.0 && m_linebreakerstate != linebreaker::state::closing && !controlled->lineBreaker.closed); - btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || controlled->lineBreaker.closed || controlled->lineBreaker.initCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); + btLampkaWylSzybki.Turn(m_linebreakerstate == linebreaker::state::closing || controlled->lineBreaker.IsClosed()); + btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !controlled->lineBreaker.IsClosed()); + btLampkaMainBreakerReady.Turn(controlled->lineBreaker.IsInitialised() && m_linebreakerstate != linebreaker::state::closing && !controlled->lineBreaker.IsClosed()); + btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || controlled->lineBreaker.IsClosed() || controlled->lineBreaker.RemainingInitTime() < 0.0 && simulation::Time.data().wMilliseconds > 500); btLampkaPrzetw.Turn(occupied->lowVoltage.power110vAvailable); btLampkaPrzetwOff.Turn(!occupied->lowVoltage.power110vAvailable); - btLampkaPrzetwAOff.Turn(!controlled->converter.running); - btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : controlled->converter.overloaded); + btLampkaPrzetwAOff.Turn(!controlled->converter.IsRunning()); + btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : controlled->converter.IsOverloaded()); - btLampkaOpory.Turn(controlled->lineContactors.closed && controlled->ResistorsFlagCheck()); + btLampkaOpory.Turn(controlled->lineContactors.IsClosed() && controlled->ResistorsFlagCheck()); btLampkaBezoporowa.Turn(controlled->ResistorsFlagCheck() || controlled->MainCtrlActualPos == 0); // do EU04 btLampkaStyczn.Turn(controlled->LineContactorsLampLit()); // mozna prowadzic rozruch - btLampkaPrzekRozn.Turn(!controlled->protection.ground && controlled->MainCircuitLampsEnabled()); // relay is off and needs a reset + btLampkaPrzekRozn.Turn(!controlled->protection.GroundHolds() && controlled->MainCircuitLampsEnabled()); // relay is off and needs a reset btLampkaNadmSil.Turn(controlled->FuseFlagCheck() && controlled->MainCircuitLampsEnabled()); // relay is off and needs a reset btLampkaUkrotnienie.Turn(controlled->Couplers[controlled->CabOccupied == 1 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)); btLampkaHamPosp.Turn(TestFlag(occupied->brakes.distributor->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania @@ -1103,8 +1103,8 @@ void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) auto const *physics{tmp->physics}; - btLampkaWylSzybkiB.Turn(physics->lineBreaker.closed); - btLampkaWylSzybkiBOff.Turn(false == physics->lineBreaker.closed + btLampkaWylSzybkiB.Turn(physics->lineBreaker.IsClosed()); + btLampkaWylSzybkiBOff.Turn(false == physics->lineBreaker.IsClosed() /*&& ( physics->MainsInitTimeCountdown <= 0.0 )*/ /*&& ( fHVoltage != 0.0 )*/); @@ -1142,13 +1142,13 @@ void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) { btLampkaHamowanie2zes.Turn(false); } - btLampkaNadmPrzetwB.Turn(physics->converter.overloaded); // nadmiarowy przetwornicy? - btLampkaPrzetwB.Turn(physics->converter.running); // zalaczenie przetwornicy - btLampkaPrzetwBOff.Turn(false == physics->converter.running); - btLampkaHVoltageB.Turn(physics->protection.noVoltage && physics->protection.overvoltage); + btLampkaNadmPrzetwB.Turn(physics->converter.IsOverloaded()); // nadmiarowy przetwornicy? + btLampkaPrzetwB.Turn(physics->converter.IsRunning()); // zalaczenie przetwornicy + btLampkaPrzetwBOff.Turn(false == physics->converter.IsRunning()); + btLampkaHVoltageB.Turn(physics->protection.UndervoltageHolds() && physics->protection.OvervoltageHolds()); btLampkaMalfunctionB.Turn(physics->diesel.heat.PA); // motor fuse indicator turns on if the fuse was blown in any unit under control - if (physics->lineBreaker.closed) + if (physics->lineBreaker.IsClosed()) { btLampkaNadmSil.Turn(btLampkaNadmSil.GetValue() || physics->FuseFlagCheck()); } @@ -1374,7 +1374,7 @@ void TTrain::updateHeatingAndInstrumentLights() { //--------- // hunter-080812: poprawka na ogrzewanie w elektrykach - usuniete uzaleznienie od przetwornicy - if (controlled->trainHeating.on == true && controlled->converter.overloaded == false) + if (controlled->trainHeating.on == true && controlled->converter.IsOverloaded() == false) btLampkaOgrzewanieSkladu.Turn(true); else btLampkaOgrzewanieSkladu.Turn(false); @@ -1383,7 +1383,7 @@ void TTrain::updateHeatingAndInstrumentLights() // lights auto const lightpower{(InstrumentLightType == 0 ? occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable : - InstrumentLightType == 1 ? controlled->lineBreaker.closed : + InstrumentLightType == 1 ? controlled->lineBreaker.IsClosed() : InstrumentLightType == 2 ? occupied->lowVoltage.power110vAvailable : InstrumentLightType == 3 ? occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable : InstrumentLightType == 4 ? occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable : @@ -1478,14 +1478,14 @@ void TTrain::updateAuxiliaryButtons(bool const lowvoltagepower) //------------ // 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 && occupied->converter.switchType != "impulse" && occupied->converter.start == start_t::manual) + if (ggConverterButton.SubModel != nullptr && occupied->converter.config.switchType != "impulse" && occupied->converter.config.start == start_t::manual) { - ggConverterButton.UpdateValue(occupied->converter.allow ? 1.f : 0.f, dsbSwitch); + ggConverterButton.UpdateValue(occupied->converter.IsAllowed() ? 1.f : 0.f, dsbSwitch); } ggConverterButton.Update(); if (ggConverterLocalButton.SubModel != nullptr) { - ggConverterLocalButton.UpdateValue(occupied->converter.allowLocal ? 1.f : 0.f, dsbSwitch); + ggConverterLocalButton.UpdateValue(occupied->converter.LocalSwitchOn() ? 1.f : 0.f, dsbSwitch); } ggConverterLocalButton.Update(); ggConverterOffButton.Update(); diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index b9f948111..ca0f4b863 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -115,7 +115,7 @@ void TDynamicObject::renderAuxiliarySounds() { auto frequency{ 1.0 }; // NBMX dzwiek przetwornicy - if( physics->converter.running ) { + if( physics->converter.IsRunning() ) { if( physics->EngineType == TEngineType::ElectricSeriesMotor ) { auto const voltage { std::max( physics->GetTrainsetHighVoltage(), physics->pantographCircuit.supplyVoltage ) }; if( voltage > 0.0 ) { @@ -1096,9 +1096,9 @@ TDynamicObject::powertrain_sounds::renderIgnitionSounds( physics::Vehicle const // engine sounds // ignition - if( engine_state_last != Vehicle.lineBreaker.closed ) { + if( engine_state_last != Vehicle.lineBreaker.IsClosed() ) { - if( true == Vehicle.lineBreaker.closed ) { + if( true == Vehicle.lineBreaker.IsClosed() ) { // TODO: separate engine and main circuit // engine activation engine_shutdown.stop(); @@ -1124,7 +1124,7 @@ TDynamicObject::powertrain_sounds::renderIgnitionSounds( physics::Vehicle const .gain( linebreaker_open.m_amplitudeoffset + linebreaker_open.m_amplitudefactor * 1.f ) .play(); } - engine_state_last = Vehicle.lineBreaker.closed; + engine_state_last = Vehicle.lineBreaker.IsClosed(); } } @@ -1136,7 +1136,7 @@ TDynamicObject::powertrain_sounds::renderEngineSounds( physics::Vehicle const &V double volume { 0.0 }; // main engine sound - if( true == Vehicle.lineBreaker.closed ) { + if( true == Vehicle.lineBreaker.IsClosed() ) { if( std::abs(Vehicle.enrot) > 0.01 // McZapkie-280503: zeby dla dumb dzialal silnik na jalowych obrotach @@ -1238,7 +1238,7 @@ TDynamicObject::powertrain_sounds::renderEngineSounds( physics::Vehicle const &V } } - if (Vehicle.lineBreaker.closed) { + if (Vehicle.lineBreaker.IsClosed()) { float power = std::clamp(Vehicle.inductionMotor.forceShare, 0.0, 1.0); fake_engine diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index b59ab45aa..d859d7674 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -274,7 +274,7 @@ void TDynamicObject::updateTractionVoltage( double const dt1 ) // Ra 2014-07: doraźna blokada logowania zimnych lokomotyw - zrobić to trzeba inaczej if( physics->pantographs[VehicleEnd::front].is_active || physics->pantographs[VehicleEnd::rear].is_active ) { - if( physics->lineBreaker.closed // Ra 15-01: logować tylko, jeśli WS załączony + if( physics->lineBreaker.IsClosed() // Ra 15-01: logować tylko, jeśli WS załączony && physics->GetTrainsetHighVoltage() < 0.1f // yB 16-03: i nie jest to asynchron zasilany z daleka && false == physics->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 @@ -420,7 +420,7 @@ void TDynamicObject::sumConsistBrakeForces( InductionBrakeState &state ) Nmax / (p->physics->NAxles * p->physics->brakes.blocksPerAxle), p->physics->brakes.blending.referenceSpeed) * 1000; // sila hamowania pn - state.FmaxED += p->physics->lineBreaker.closed && p->physics->DirActive != 0 && p->physics->inductionMotor.inverterRatio == 1.0 && + state.FmaxED += p->physics->lineBreaker.IsClosed() && p->physics->DirActive != 0 && p->physics->inductionMotor.inverterRatio == 1.0 && p->physics->inductionMotor.braking.maxForce * p->physics->NPoweredAxles > 0 ? p->physics->inductionMotor.braking.maxForce * 1000 : 0; // chwilowy max ED -> do rozdzialu sil @@ -734,7 +734,7 @@ void TDynamicObject::recordMedState( InductionBrakeState const &state, double co void TDynamicObject::switchOffMainsWithoutBattery() { // fragment "z EXE Kursa" - if( physics->lineBreaker.closed ) { // nie wchodzić w funkcję bez potrzeby + if( physics->lineBreaker.IsClosed() ) { // nie wchodzić w funkcję bez potrzeby if( false == (physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable) /* // NOTE: disabled on account of multi-unit setups, where the unmanned unit wouldn't be affected @@ -1512,7 +1512,7 @@ void TDynamicObject::Damage(char flag) if (flag & 2) //usterka sterowania { - physics->lineContactors.closed = false; + physics->lineContactors.Open(); if (physics->InitialCtrlDelay<100000000) physics->InitialCtrlDelay += 100000001; } @@ -1524,8 +1524,8 @@ void TDynamicObject::Damage(char flag) if (flag & 4) //blokada przetwornicy { - if( physics->converter.start != start_t::disabled ) { - physics->converter.overloaded = true; + if( physics->converter.config.start != start_t::disabled ) { + physics->converter.Overload(); } } else diff --git a/vehicle/enginestart.cpp b/vehicle/enginestart.cpp index ebac38066..99757effa 100644 --- a/vehicle/enginestart.cpp +++ b/vehicle/enginestart.cpp @@ -103,7 +103,7 @@ bool remote_switch::open(physics::Vehicle &Engine) { } bool remote_switch::is_running(physics::Vehicle const &Engine) { - return Engine.lineBreaker.closed || Engine.diesel.startupRequested; + return Engine.lineBreaker.IsClosed() || Engine.diesel.startupRequested; } } // namespace engine_start diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index 6bb8274b9..ecada0130 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -70,9 +70,9 @@ void ui::vehicleparams_panel::draw_mini(const physics::Vehicle &physics) if (physics.lowVoltage.batteryOn) draw_infobutton(STR_C("bat."), ImVec2(120, 55)); - if (physics.lineBreaker.closed) + if (physics.lineBreaker.IsClosed()) draw_infobutton(STR_C("main.")); - if (physics.converter.running) + if (physics.converter.IsRunning()) draw_infobutton(STR_C("conv.")); if (physics.air.compressor.running) draw_infobutton(STR_C("comp.")); @@ -148,12 +148,12 @@ void ui::vehicleparams_panel::render_contents() std::snprintf(buffer.data(), buffer.size(), STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s%s%s%.0f@%.0f"), // devices - (physics.lowVoltage.batteryOn ? 'B' : '.'), (physics.lineBreaker.closed ? 'M' : '.'), (physics.FuseFlag ? '!' : '.'), (physics.pantographs[VehicleEnd::rear].is_active ? (physics.pantographCircuit.rearVoltage > 0.0 ? 'O' : 'o') : '.'), + (physics.lowVoltage.batteryOn ? 'B' : '.'), (physics.lineBreaker.IsClosed() ? 'M' : '.'), (physics.FuseFlag ? '!' : '.'), (physics.pantographs[VehicleEnd::rear].is_active ? (physics.pantographCircuit.rearVoltage > 0.0 ? 'O' : 'o') : '.'), (physics.pantographs[VehicleEnd::front].is_active ? (physics.pantographCircuit.frontVoltage > 0.0 ? 'P' : 'p') : '.'), (physics.pantographAir.pressureLockActive ? '!' : (physics.pantographAir.pressureSwitchActive ? '*' : '.')), (physics.WaterPump.is_active ? 'W' : (false == physics.WaterPump.breaker ? '-' : (physics.WaterPump.is_enabled ? 'w' : '.'))), (true == physics.WaterHeater.is_damaged ? '!' : (physics.WaterHeater.is_active ? 'H' : (false == physics.WaterHeater.breaker ? '-' : (physics.WaterHeater.is_enabled ? 'h' : '.')))), (physics.FuelPump.is_active ? 'F' : (physics.FuelPump.is_enabled ? 'f' : '.')), (physics.OilPump.is_active ? 'O' : (physics.OilPump.is_enabled ? 'o' : '.')), - (false == physics.converter.allowLocal ? '-' : (physics.converter.allow ? (physics.converter.running ? 'X' : 'x') : '.')), (physics.converter.overloaded ? '!' : '.'), + (false == physics.converter.LocalSwitchOn() ? '-' : (physics.converter.IsAllowed() ? (physics.converter.IsRunning() ? 'X' : 'x') : '.')), (physics.converter.IsOverloaded() ? '!' : '.'), (physics.air.compressor.running ? 'C' : (false == physics.air.compressor.allowLocal ? '-' : ((physics.air.compressor.allow || physics.air.compressor.start == start_t::automatic) ? 'c' : '.'))), (physics.air.compressor.governorLock ? '!' : '.'), "", std::string(isdieselenginepowered ? STR(" oil pressure: ") + to_string(physics.OilPump.pressure, 2) : "").c_str(), // power transfers From 160ffe2147b53677af302640c387c10399aedc06 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 10:08:54 +0100 Subject: [PATCH 08/30] refactor(physics): the low voltage, the train heating and the pantographs keep their state to themselves As the parts of the main circuit: the battery and the low voltage circuits, the train heating, the circuit of the pantographs and their air become classes with the definition in `config` and the state behind queries and operations. The step of the air of the pantographs (the small compressor, the three-way cock, the leaks, the pressure switch) moves into PantographAir::Update(), which gets what it needs as plain values (PantographAirSupply) and reports a trip of the pressure switch, so the vehicle opens its line breaker or switches the converter of a unit off as before. The drain of the battery and its limits move into LowVoltageSupply. The latch of the held battery button of the cab moves from the physics to TTrain, where the button is. The gauges of the cab bind to the values they show through const pointers (TGauge::Assign*() take them), so the queries they bind to return const references and the cab reads the state live without being able to change it. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- application/driverhints.cpp | 28 +-- application/driveruipanels.cpp | 14 +- input/messaging.cpp | 2 +- physics/components/body.cpp | 4 +- physics/components/cab.cpp | 4 +- physics/components/collisions.cpp | 2 +- physics/components/commands.cpp | 8 +- physics/components/diesel.cpp | 22 +- physics/components/doors.cpp | 6 +- physics/components/drive.cpp | 10 +- physics/components/electrics.cpp | 196 ++++++----------- physics/components/fizsections.cpp | 29 +-- physics/components/lowvoltage.h | 123 +++++++++-- physics/components/pantographs.h | 197 ++++++++++++++++-- physics/components/pneumatics.cpp | 10 +- physics/components/securitysystem.cpp | 4 +- physics/components/setup.cpp | 8 +- physics/components/traction.cpp | 14 +- physics/vehicle.h | 4 +- rendering/lightarray.cpp | 4 +- simulation/blackboxrecorder.cpp | 4 +- tests/unit/drive.cpp | 14 +- tests/unit/golden.cpp | 6 +- tests/unit/invariants.cpp | 8 +- tests/unit/test_auxiliaries.cpp | 56 ++--- tests/unit/test_commands.cpp | 6 +- tests/unit/test_compartment_lights.cpp | 20 +- tests/unit/test_compartment_lights_switch.cpp | 2 +- tests/unit/test_compressor.cpp | 10 +- tests/unit/test_controls.cpp | 10 +- tests/unit/test_engine_shutdown.cpp | 2 +- tests/unit/test_genset.cpp | 18 +- tests/unit/test_horn.cpp | 10 +- tests/unit/test_line_contactors_interlock.cpp | 12 +- tests/unit/test_mains_before_pantographs.cpp | 40 ++-- tests/unit/test_oil_pump.cpp | 8 +- tests/unit/test_pressure_switch.cpp | 10 +- tests/unit/test_pullee.cpp | 20 +- tests/unit/test_radio.cpp | 14 +- tests/unit/test_switches.cpp | 4 +- tests/unit/vehicle.cpp | 8 +- vehicle/Gauge.cpp | 8 +- vehicle/Gauge.h | 16 +- vehicle/Train.h | 1 + vehicle/ai/consist.cpp | 10 +- vehicle/ai/controls.cpp | 2 +- vehicle/ai/engine.cpp | 16 +- vehicle/ai/orders.cpp | 2 +- vehicle/ai/situation.cpp | 22 +- vehicle/cab/auxiliarycommands.cpp | 2 +- vehicle/cab/cabcommands.cpp | 30 +-- vehicle/cab/equipmentcommands.cpp | 10 +- vehicle/cab/pantographcommands.cpp | 32 +-- vehicle/cab/setup.cpp | 16 +- vehicle/cab/sounds.cpp | 2 +- vehicle/cab/train.cpp | 18 +- vehicle/cab/update.cpp | 52 ++--- vehicle/dynamic/destinations.cpp | 2 +- vehicle/dynamic/lifecycle.cpp | 3 +- vehicle/dynamic/sounds.cpp | 12 +- vehicle/dynamic/update.cpp | 68 +++--- vehicle/dynamic/visual.cpp | 4 +- widgets/vehicleparams.cpp | 8 +- 63 files changed, 746 insertions(+), 561 deletions(-) diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 0f49b1933..7336b18dd 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -89,7 +89,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->lowVoltage.batteryStart != start_t::manual || occupied->lowVoltage.power24vAvailable == true; } ); + return occupied->lowVoltage.config.batteryStart != start_t::manual || occupied->lowVoltage.Is24vAvailable() == true; } ); break; } case driver_hint::batteryoff: { @@ -100,12 +100,12 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->lowVoltage.batteryStart != start_t::manual || occupied->lowVoltage.power24vAvailable == false; } ); + return occupied->lowVoltage.config.batteryStart != start_t::manual || occupied->lowVoltage.Is24vAvailable() == false; } ); break; } // battery case driver_hint::cabactivation: { - if (AIControllFlag && occupied->lowVoltage.power24vAvailable) { + if (AIControllFlag && occupied->lowVoltage.Is24vAvailable()) { occupied->CabActivisation(); CheckVehicles(); } @@ -224,46 +224,46 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // pantographs case driver_hint::pantographairsourcesetmain: { if( AIControllFlag ) { - pantographUnit->pantographAir.connectedToMainReservoir = true; + pantographUnit->pantographAir.ConnectToMainReservoir(true); } remove_hint( driver_hint::pantographairsourcesetauxiliary ); hint( Action, [this](float const /*Parameter*/) { - return pantographUnit->pantographAir.connectedToMainReservoir == true; } ); + return pantographUnit->pantographAir.IsConnectedToMainReservoir() == true; } ); break; } case driver_hint::pantographairsourcesetauxiliary: { if( AIControllFlag ) { - pantographUnit->pantographAir.connectedToMainReservoir = false; + pantographUnit->pantographAir.ConnectToMainReservoir(false); } remove_hint( driver_hint::pantographcompressoron ); hint( Action, [this](float const /*Parameter*/) { - return pantographUnit->pantographAir.connectedToMainReservoir == false; } ); + return pantographUnit->pantographAir.IsConnectedToMainReservoir() == false; } ); break; } case driver_hint::pantographcompressoron: { if( AIControllFlag ) { - pantographUnit->pantographAir.compressorRunning = true; + pantographUnit->pantographAir.SwitchCompressor(true); } remove_hint( driver_hint::pantographcompressoroff ); hint( Action, [this](float const /*Parameter*/) { - return pantographUnit->pantographAir.compressorRunning == true; } ); + return pantographUnit->pantographAir.IsCompressorRunning() == true; } ); break; } case driver_hint::pantographcompressoroff: { if( AIControllFlag ) { - pantographUnit->pantographAir.compressorRunning = false; + pantographUnit->pantographAir.SwitchCompressor(false); } remove_hint( driver_hint::pantographcompressoron ); hint( Action, [this](float const /*Parameter*/) { - return pantographUnit->pantographAir.compressorRunning == false; } ); + return pantographUnit->pantographAir.IsCompressorRunning() == false; } ); break; } case driver_hint::pantographsvalveon: { @@ -760,7 +760,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return pantographUnit->pantographAir.pressure >= (is_emu() ? (pantographUnit->pantographAir.pressureLockActive ? 4.6 : 2.6) : 4.2); } ); + return pantographUnit->pantographAir.Pressure() >= (is_emu() ? (pantographUnit->pantographAir.IsPressureLockActive() ? 4.6 : 2.6) : 4.2); } ); break; } case driver_hint::waitbrakecharge: { @@ -1218,7 +1218,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->trainHeating.allow == true; } ); + return occupied->trainHeating.IsAllowed() == true; } ); break; } case driver_hint::consistheatingoff: { @@ -1229,7 +1229,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->trainHeating.allow == false; } ); + return occupied->trainHeating.IsAllowed() == false; } ); break; } diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 493f65ce5..6ddc9aa4f 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -816,7 +816,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s[%.0f]%s%.0f@%.0f :: %.0f@%.0f%s[%.0f]%s%.0f@%.0f"), // devices - physics.lowVoltage.batteryOn ? 'B' : '.', + physics.lowVoltage.IsBatteryOn() ? 'B' : '.', physics.pantographAir.valve.is_active ? '+' : '.', physics.pantographs[VehicleEnd::rear].valve.is_active ? 'O' : physics.pantographs[VehicleEnd::rear].valve.is_enabled ? 'o' : @@ -824,8 +824,8 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.pantographs[VehicleEnd::front].valve.is_active ? 'P' : physics.pantographs[VehicleEnd::front].valve.is_enabled ? 'p' : '.', - physics.pantographAir.pressureLockActive ? '!' : - physics.pantographAir.pressureSwitchActive ? '*' : + physics.pantographAir.IsPressureLockActive() ? '!' : + physics.pantographAir.IsPressureSwitchPrimed() ? '*' : '.', physics.WaterPump.is_active ? 'W' : false == physics.WaterPump.breaker ? '-' : @@ -858,8 +858,8 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.protection.PressureSwitchTripped() ? '!' : physics.lineContactors.IsClosed() ? '+' : '.', - physics.trainHeating.on ? 'H' : - physics.trainHeating.allow ? 'h' : + physics.trainHeating.IsOn() ? 'H' : + physics.trainHeating.IsAllowed() ? 'h' : '.', physics.brakes.distributor->Releaser() ? '^' : '.', std::string( m_input.mechanik ? STR(" R") + ( physics.Radio && physics.RadioFuse ? std::to_string( m_input.mechanik->iRadioChannel ) : "-" ) : "" ).c_str(), @@ -951,8 +951,8 @@ debug_panel::update_section_vehicle( std::vector &Output ) { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C(" pantograph: %.2f%cMT"), - physics.pantographAir.pressure, - physics.pantographAir.connectedToMainReservoir ? '-' : '|' ); + physics.pantographAir.Pressure(), + physics.pantographAir.IsConnectedToMainReservoir() ? '-' : '|' ); textline += m_buffer.data(); } diff --git a/input/messaging.cpp b/input/messaging.cpp index 64a0a74f8..e58483baa 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -329,7 +329,7 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) Vehicle->physics->ShowCurrent(p + 1); // amperomierze kolejnych grup // WriteLog("zapisalem prady"); r.iPar[30] = Vehicle->physics->WarningSignal; // trabienie - r.fPar[31] = Vehicle->physics->pantographCircuit.supplyVoltage; // napiecie WN + r.fPar[31] = Vehicle->physics->pantographCircuit.SupplyVoltage(); // napiecie WN // WriteLog("Parametry gotowe"); i <<= 2; // ilość bajtów r.cString[i] = char(j); // na końcu nazwa, żeby jakoś zidentyfikować diff --git a/physics/components/body.cpp b/physics/components/body.cpp index 30d19d59c..2e3c533d4 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -525,9 +525,7 @@ void physics::Vehicle::compute_movement_(double const Deltatime) PowerCouplersCheck(Deltatime, Coupling::power110v); PowerCouplersCheck(Deltatime, Coupling::power24v); - lowVoltage.power24vVoltage = std::max(PowerCircuits[0].first, GetTrainsetVoltage(Coupling::power24v)); - lowVoltage.power24vAvailable = lowVoltage.power24vVoltage > 0; - lowVoltage.power110vAvailable = PowerCircuits[1].first > 0 || GetTrainsetVoltage(Coupling::power110v) > 0; + lowVoltage.SetSupply(std::max(PowerCircuits[0].first, GetTrainsetVoltage(Coupling::power24v)), PowerCircuits[1].first > 0 || GetTrainsetVoltage(Coupling::power110v) > 0); } // ************************************************************************************************* diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index cf9e52321..ed68b611c 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -74,7 +74,7 @@ int physics::Vehicle::SoundingHorns(int const Signal) const auto const supplied{[this](horn_supply const Supply) { if (Supply == horn_supply::electric) { - return lowVoltage.power24vAvailable || lowVoltage.power110vAvailable; + return lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable(); } if (air.mainReservoirVolume > 0.0) { @@ -204,7 +204,7 @@ bool physics::Vehicle::PulleeModeSwitch(bool const State) DecManualBrakeLevel(ManualBrakePosNo); brakes.spring.activate = false; SecuritySystem.set_enabled(false); - lowVoltage.batteryOn = false; + lowVoltage.DisconnectBattery(); } return true; } diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index e46bae097..8f985fe39 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -238,7 +238,7 @@ collision::vehicle_kind physics::Vehicle::collision_kind() const auto const unit{is_multiple_unit()}; 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 && trainHeating.power > 0.0), false); + return collision::kind_of(powered, unit || passengers || (false == powered && trainHeating.config.power > 0.0), false); } collision::crush_curve physics::Vehicle::crush_curve_at(VehicleEnd const End) const diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 875431621..80b8c153d 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -325,7 +325,7 @@ bool physics::Vehicle::RunBrakeEquipmentCommand(VehicleCommand const Command, do } else if (Command == VehicleCommand::springBrakeActivate) { - if (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) + if (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) { brakes.spring.activate = CValue1 > 0; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); @@ -370,9 +370,9 @@ bool physics::Vehicle::RunAuxiliariesCommand(VehicleCommand const Command, doubl else if (Command == VehicleCommand::batterySwitch) /*NBMX*/ { // the battery of a vehicle prepared for hauling (PulleeMode) stays off - if (lowVoltage.batteryStart == start_t::manual && (false == PulleeMode || CValue1 <= 0.0)) + if (false == PulleeMode || CValue1 <= 0.0) { - lowVoltage.batteryOn = CValue1 > 0.0; + lowVoltage.SwitchBattery(CValue1 > 0.0); } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } @@ -690,7 +690,7 @@ void physics::Vehicle::DoorRemoteCommand(bool const Open, double const CValue1, { using enum control_t; if (auto const doorcontrol{Open ? Doors.open_control : Doors.close_control}; - (doorcontrol != conductor && doorcontrol != driver && doorcontrol != mixed) || (false == lowVoltage.power24vAvailable && false == lowVoltage.power110vAvailable)) + (doorcontrol != conductor && doorcontrol != driver && doorcontrol != mixed) || (false == lowVoltage.Is24vAvailable() && false == lowVoltage.Is110vAvailable())) { return; } diff --git a/physics/components/diesel.cpp b/physics/components/diesel.cpp index decd11eb5..489892607 100644 --- a/physics/components/diesel.cpp +++ b/physics/components/diesel.cpp @@ -50,7 +50,7 @@ double physics::Vehicle::EngineMaxRPM() const void physics::Vehicle::WaterPumpCheck(double const /*Timestep*/) { // NOTE: breaker override with start type is sm42 specific hack, replace with ability to define the presence of the breaker - WaterPump.is_active = true == (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) && true == WaterPump.breaker && false == WaterPump.is_disabled && + WaterPump.is_active = true == (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) && true == WaterPump.breaker && false == WaterPump.is_disabled && (true == WaterPump.is_active || true == WaterPump.is_enabled || WaterPump.start_type == start_t::battery); } @@ -58,7 +58,7 @@ void physics::Vehicle::WaterPumpCheck(double const /*Timestep*/) void physics::Vehicle::WaterHeaterCheck(double const /*Timestep*/) { - WaterHeater.is_active = false == WaterHeater.is_damaged && true == (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) && true == WaterHeater.is_enabled && true == WaterHeater.breaker && + WaterHeater.is_active = false == WaterHeater.is_damaged && true == (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) && true == WaterHeater.is_enabled && true == WaterHeater.breaker && (WaterHeater.is_active || WaterHeater.config.temp_min < 0 || diesel.heat.temperatura1 < WaterHeater.config.temp_min); WaterHeater.is_damaged = true == WaterHeater.is_damaged || (true == WaterHeater.is_active && false == WaterPump.is_active); @@ -74,7 +74,7 @@ void physics::Vehicle::FuelPumpCheck(double const /*Timestep*/) { using enum start_t; - FuelPump.is_active = true == (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) && false == FuelPump.is_disabled && + FuelPump.is_active = true == (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) && false == FuelPump.is_disabled && (FuelPump.is_active || (FuelPump.start_type == manual ? FuelPump.is_enabled : FuelPump.start_type == automatic ? diesel.startupRequested || lineBreaker.IsClosed() : FuelPump.start_type == manualwithautofallback ? FuelPump.is_enabled || diesel.startupRequested || lineBreaker.IsClosed() : @@ -85,7 +85,7 @@ void physics::Vehicle::FuelPumpCheck(double const /*Timestep*/) void physics::Vehicle::OilPumpCheck(double const Timestep) { - OilPump.is_active = true == (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) && false == lineBreaker.IsClosed() && false == OilPump.is_disabled && + OilPump.is_active = true == (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) && false == lineBreaker.IsClosed() && false == OilPump.is_disabled && (OilPump.is_active || (OilPump.start_type == start_t::manual ? OilPump.is_enabled : OilPump.start_type == start_t::automatic ? diesel.startupRequested : OilPump.start_type == start_t::manualwithautofallback ? OilPump.is_enabled || diesel.startupRequested : @@ -341,10 +341,10 @@ double physics::Vehicle::DieselElectricTargetRevolutions() else tmp = DElist[protection.PressureSwitchTripped() ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; - if (true == trainHeating.allow && trainHeating.power > 0 && trainHeating.engineRpm > 0) + if (true == trainHeating.IsAllowed() && trainHeating.config.power > 0 && trainHeating.config.engineRpm > 0) { // bump engine revolutions up if needed, when heating is on - tmp = std::max(tmp, std::min(EngineMaxRPM(), trainHeating.engineRpm) / 60.0); + tmp = std::max(tmp, std::min(EngineMaxRPM(), trainHeating.config.engineRpm) / 60.0); } // NOTE: fake diesel.fill calculation for the sake of smoke emitter which uses this parameter to determine smoke opacity diesel.fill = std::clamp(0.2 + 0.35 * (tmp - enrot) + 0.5 * (std::abs(Im) / DElist[MainCtrlPosNo].Imax), 0.05, 1.0); @@ -385,9 +385,9 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) auto power = Power; tempImax = DElist[MainCtrlPos].Imax; tempUmax = DElist[MainCtrlPos].Umax; - if (true == trainHeating.on) + if (true == trainHeating.IsOn()) { - power -= trainHeating.power; + power -= trainHeating.config.power; } power = std::max(power, 0.0); // NOTE: very crude way to approximate power generated at current rpm instead of instant top output @@ -1373,7 +1373,7 @@ void physics::Vehicle::dizel_Heat(double const dt) // engine heat transfers auto const Ge{engineon * (0.21 * diesel.heat.powerfactor * EnginePower + 12) / 3600}; // TODO: replace fixed heating power cost with more accurate calculation - auto const obciazenie{engineon * (diesel.heat.powerfactor * EnginePower / 950 + (trainHeating.on ? trainHeating.power : 0) + 70)}; + auto const obciazenie{engineon * (diesel.heat.powerfactor * EnginePower / 950 + (trainHeating.IsOn() ? trainHeating.config.power : 0) + 70)}; auto const Qd{qs * Ge - obciazenie}; // silnik oddaje czesc ciepla do wody chlodzacej, a takze pewna niewielka czesc do otoczenia, modyfikowane przez okienko auto const Qs{(Qd - diesel.heat.kfs * (diesel.heat.Ts - diesel.heat.Tsr) - diesel.heat.kfe * /* ( 0.3 + 0.7 * ( diesel.heat.okienko ? 1 : 0 ) ) * */ (diesel.heat.Ts - diesel.heat.Te))}; @@ -1400,7 +1400,7 @@ void physics::Vehicle::dizel_Heat(double const dt) { // auxiliary water circuit setup diesel.heat.water_aux.is_warm = true == diesel.heat.cooling || - (true == lineBreaker.IsClosed() && lowVoltage.batteryVoltage > 0.75 * lowVoltage.nominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ + (true == lineBreaker.IsClosed() && lowVoltage.BatteryVoltage() > 0.75 * lowVoltage.config.nominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ && diesel.heat.water_aux.config.temp_cooling > 0 && diesel.heat.temperatura2 > diesel.heat.water_aux.config.temp_cooling - (diesel.heat.water_aux.is_warm ? 8 : 0)); auto const PTC2{(diesel.heat.water_aux.is_warm /*or PTC2p*/ ? 1 : 0)}; diesel.heat.rpmwz2 = static_cast(PTC2 * (diesel.heat.fan_speed >= 0 ? rpm * diesel.heat.fan_speed : diesel.heat.fan_speed * -1)); @@ -1423,7 +1423,7 @@ void physics::Vehicle::dizel_Heat(double const dt) diesel.heat.water.is_flowing = diesel.heat.water.config.temp_flow < 0 || diesel.heat.temperatura1 > diesel.heat.water.config.temp_flow - (diesel.heat.water.is_flowing ? 5 : 0); auto const obieg{(diesel.heat.water.is_flowing ? 1 : 0)}; diesel.heat.water.is_warm = - true == diesel.heat.cooling || (true == lineBreaker.IsClosed() && lowVoltage.batteryVoltage > 0.75 * lowVoltage.nominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ + true == diesel.heat.cooling || (true == lineBreaker.IsClosed() && lowVoltage.BatteryVoltage() > 0.75 * lowVoltage.config.nominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ && diesel.heat.water.config.temp_cooling > 0 && diesel.heat.temperatura1 > diesel.heat.water.config.temp_cooling - (diesel.heat.water.is_warm ? 8 : 0)); auto const PTC1{(diesel.heat.water.is_warm /*or PTC1p*/ ? 1 : 0)}; diesel.heat.rpmwz = static_cast(PTC1 * (diesel.heat.fan_speed >= 0 ? rpm * diesel.heat.fan_speed : diesel.heat.fan_speed * -1)); diff --git a/physics/components/doors.cpp b/physics/components/doors.cpp index 613d33da4..e1afcdba1 100644 --- a/physics/components/doors.cpp +++ b/physics/components/doors.cpp @@ -281,7 +281,7 @@ bool physics::Vehicle::OperateDoors(VehicleSide const Door, bool const State, ra else { // remote door operation signals require power to propagate - if (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) + if (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) { door.remote_open = State; door.remote_close = false == State; @@ -486,9 +486,9 @@ bool physics::Vehicle::doors_powered() const } if (Doors.voltage == 24) { - return lowVoltage.power24vAvailable || lowVoltage.power110vAvailable; + return lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable(); } - return Doors.voltage == 110 && lowVoltage.power110vAvailable; + return Doors.voltage == 110 && lowVoltage.Is110vAvailable(); } // whether the unfolded step folds: without the permission to stay out, or with the door closing, once it's about to diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index 309a040ba..d11d02638 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -125,7 +125,7 @@ void updateRadiatorFans(physics::Vehicle &vehicle, double const dt) // else it needs the voltage of the source bool linePowerAvailable(physics::Vehicle const &vehicle) { - return vehicle.lineBreaker.config.pantographsRequireIt ? vehicle.lowVoltage.power24vAvailable || vehicle.lowVoltage.power110vAvailable : vehicle.EnginePowerSourceVoltage() > 0.5 * vehicle.EnginePowerSource.MaxVoltage; + return vehicle.lineBreaker.config.pantographsRequireIt ? vehicle.lowVoltage.Is24vAvailable() || vehicle.lowVoltage.Is110vAvailable() : vehicle.EnginePowerSourceVoltage() > 0.5 * vehicle.EnginePowerSource.MaxVoltage; } // a notch of the master controller of the drives without steps of their own (no engine, Dumb, diesel-electric, @@ -199,7 +199,7 @@ public: } bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override { - return vehicle.lowVoltage.power24vAvailable; + return vehicle.lowVoltage.Is24vAvailable(); } bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override { @@ -259,7 +259,7 @@ public: void CheckVoltageRelays(physics::Vehicle &vehicle) const override { // update the state of voltage relays - auto const voltage{std::max(vehicle.GetTrainsetHighVoltage(), vehicle.pantographCircuit.supplyVoltage)}; + auto const voltage{std::max(vehicle.GetTrainsetHighVoltage(), vehicle.pantographCircuit.SupplyVoltage())}; // where the line breaker holds without voltage (closed ahead of the pantographs) the undervoltage relay opens the // line contactors instead, see MotorConnectorsCheck(). it picks up again only with the master controller back // where a start begins, as the line breaker it stands in for wouldn't close on a running position either: at @@ -422,7 +422,7 @@ public: } bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override { - return vehicle.lowVoltage.power24vAvailable; + return vehicle.lowVoltage.Is24vAvailable(); } bool UpdateEngine(physics::Vehicle &vehicle, double const dt) const override { @@ -524,7 +524,7 @@ public: } bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override { - return vehicle.lowVoltage.power24vAvailable; + return vehicle.lowVoltage.Is24vAvailable(); } void CheckVoltageRelays(physics::Vehicle &vehicle) const override { diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index 3f426e9d3..09b9b3290 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -34,87 +34,40 @@ http://mozilla.org/MPL/2.0/. // KURS90 - sprężarka pantografów; Ra 2014-07: teraz jest to zbiornik rozrządu, chociaż to jeszcze nie tak void physics::Vehicle::UpdatePantVolume(double dt) { - // check the pantograph compressor while at it - // TODO: move the check to a separate method - // automatic start if the pressure is too low - pantographAir.compressorRunning |= pantographAir.pressure < 4.2 && true == (pantographs[VehicleEnd::front].is_active | pantographs[VehicleEnd::rear].is_active) // TODO: any_pantograph_is_active method - && (pantographAir.compressorStart == start_t::automatic || pantographAir.compressorStart == start_t::manualwithautofallback); - - auto const lowvoltagepower{lowVoltage.power24vAvailable || lowVoltage.power110vAvailable}; - pantographAir.compressorRunning &= lowvoltagepower; - - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector // tylko jeśli pantografujący - && EnginePowerSource.CollectorParameters.CollectorsNo > 0) + if (pantographAir.Update(PantographAirSupplyNow(), dt)) { - // Ra 2014-07: zasadniczo, to istnieje zbiornik rozrządu i zbiornik pantografów - na razie mamy razem - // Ra 2014-07: kurek trójdrogowy łączy spr.pom. z pantografami i wyłącznikiem ciśnieniowym WS - // Ra 2014-07: zbiornika rozrządu nie pompuje się tu, tylko pantografy; potem można zamknąć - // WS i odpalić resztę - if (pantographAir.autoValve ? pantographAir.pressure < mainPipe.pressure : pantographAir.connectedToMainReservoir) // kurek zamyka połączenie z ZG - { // zbiornik pantografu połączony ze zbiornikiem głównym - małą sprężarką się tego nie napompuje - // Ra 2013-12: Niebugocław mówi, że w EZT nie ma potrzeby odcinać kurkiem - pantographAir.pressure = mainPipe.pressure; - // ograniczenie ciśnienia do MaxPress (tylko w pantografach!) - pantographAir.pressure = safe_clamp(mainPipe.pressure, 0.0, EnginePowerSource.CollectorParameters.MaxPress); - pantographAir.volume = (pantographAir.pressure + 1.0) * 0.1; // objętość, na wypadek odcięcia kurkiem - } - else - { // zbiornik główny odcięty, można pompować pantografy - if (pantographAir.compressorRunning) - { - // włączona mała sprężarka - pantographAir.volume += dt - // Ra 2013-12: Niebugocław mówi, że w EZT nabija 1.5 raz wolniej niż jak było 0.005 - * (TrainType == train_type::emu ? 0.003 : 0.005) / std::max(1.0, pantographAir.pressure) * (0.45 - (0.1 / pantographAir.volume / 10 - 0.1)) / 0.45; - } - pantographAir.pressure = safe_clamp(10.0 * pantographAir.volume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika - } - if (!pantographAir.compressorRunning && pantographAir.volume > 0.1) - pantographAir.volume -= dt * 0.0003 * std::max(1.0, pantographAir.pressure * 0.5); // nieszczelności: 0.0003=0.3l/s + PantPressureSwitchTrip(); + } +} - PantPressureSwitchCheck(); - } - else - { // a tu coś dla SM42 i SM31, aby pokazywać na manometrze - pantographAir.pressure = brakes.controlReservoirPressure; - } -}; +// what the air of the pantographs needs to know in the step +physics::PantographAirSupply physics::Vehicle::PantographAirSupplyNow() const +{ + PantographAirSupply supply; + supply.anyPantographActive = pantographs[VehicleEnd::front].is_active || pantographs[VehicleEnd::rear].is_active; + supply.lowVoltage = lowVoltage.IsAvailable(); + // tylko jeśli pantografujący + supply.collectors = EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0; + supply.multipleUnit = TrainType == train_type::emu; + supply.mainReservoirPressure = mainPipe.pressure; + supply.controlReservoirPressure = brakes.controlReservoirPressure; + supply.maxPressure = EnginePowerSource.CollectorParameters.MaxPress; + supply.minPressure = EnginePowerSource.CollectorParameters.MinPress; + return supply; +} // 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 physics::Vehicle::PantPressureSwitchCheck() { - if (pantographAir.pressure < EnginePowerSource.CollectorParameters.MinPress) + if (pantographAir.UpdatePressureSwitch(PantographAirSupplyNow())) { - // 3.5 wg http://www.transportszynowy.pl/eu06-07pneumat.php - if (true == pantographAir.pressureSwitchActive) - { - PantPressureSwitchTrip(); - } - } - else if (pantographAir.pressure >= 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 == lowVoltage.power24vAvailable || true == lowVoltage.power110vAvailable) - { - // prime the pressure switch - pantographAir.pressureSwitchActive = true; - // turn off the subsystems lock - pantographAir.pressureLockActive = false; - } - - if (pantographAir.pressure >= 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) - pantographAir.compressorRunning = false; - } + PantPressureSwitchTrip(); } } -// 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 +// the pantographs' pressure switch tripped by the low pressure (pantographAir spent the switch, and locked a unit): the line +// breaker opened, unless the voltage comes from elsewhere, or the converter of a unit switched off void physics::Vehicle::PantPressureSwitchTrip() { // opuszczenie pantografów przy niskim ciśnieniu @@ -132,52 +85,44 @@ void physics::Vehicle::PantPressureSwitchTrip() { // specialized variant for EMU -- pwr system disables converter and heating, // and prevents their activation until pressure switch is set again - pantographAir.pressureLockActive = 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 - pantographAir.pressureSwitchActive = false; } void physics::Vehicle::UpdateBatteryVoltage(double dt) { // przeliczenie obciążenia baterii using enum TEngineType; - if (lowVoltage.batteryVoltage > 0 && EngineType != DieselEngine && EngineType != WheelsDriven && lowVoltage.nominalBatteryVoltage > 0) + if (lowVoltage.BatteryVoltage() > 0 && EngineType != DieselEngine && EngineType != WheelsDriven && lowVoltage.config.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{lowVoltage.power110vAvailable || (EngineType == DieselElectric && true == lineBreaker.IsClosed()) || (EngineType == DieselEngine && true == lineBreaker.IsClosed())}; + auto const converteractive{lowVoltage.Is110vAvailable() || (EngineType == DieselElectric && true == lineBreaker.IsClosed()) || (EngineType == DieselEngine && true == lineBreaker.IsClosed())}; - lowVoltage.batteryVoltage -= BatteryDrain(dt, converteractive); - if (lowVoltage.nominalBatteryVoltage / lowVoltage.batteryVoltage > 1.57 && MainSwitch(false) && EngineType != DieselEngine && EngineType != WheelsDriven) + if (lowVoltage.DrainBattery(BatteryDrain(dt, converteractive)) && MainSwitch(false) && EngineType != DieselEngine && EngineType != WheelsDriven) EventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia - if (lowVoltage.batteryVoltage > lowVoltage.nominalBatteryVoltage) - lowVoltage.batteryVoltage = lowVoltage.nominalBatteryVoltage; // wstrzymanie ładowania pow. 110V - if (lowVoltage.batteryVoltage < 0.01) - lowVoltage.batteryVoltage = 0.01; } else { // TODO: check and implement proper way to handle this for diesel engines - lowVoltage.batteryVoltage = lowVoltage.nominalBatteryVoltage; + lowVoltage.KeepBatteryCharged(); } }; // the drop of the battery's voltage in dt, by what draws from it, or its rise by the converter charging it double physics::Vehicle::BatteryDrain(double dt, bool const converteractive) const { - if (lowVoltage.nominalBatteryVoltage / lowVoltage.batteryVoltage < 1.22 && lowVoltage.batteryOn) + if (lowVoltage.config.nominalBatteryVoltage / lowVoltage.BatteryVoltage() < 1.22 && lowVoltage.IsBatteryOn()) { // 110V return BatteryDrainCharged(dt, converteractive); } - if (lowVoltage.nominalBatteryVoltage / lowVoltage.batteryVoltage >= 1.22 && lowVoltage.batteryOn) + if (lowVoltage.config.nominalBatteryVoltage / lowVoltage.BatteryVoltage() >= 1.22 && lowVoltage.IsBatteryOn()) { // 90V return BatteryDrainLow(dt, converteractive); } - if (!lowVoltage.batteryOn) + if (!lowVoltage.IsBatteryOn()) { return BatteryDrainSwitchedOff(dt); } @@ -223,7 +168,7 @@ double physics::Vehicle::BatteryDrainLow(double dt, bool const converteractive) double sn3; double sn4; double sn5; - if (pantographAir.compressorRunning) + if (pantographAir.IsCompressorRunning()) sn1 = dt * 0.0046; else sn1 = 0; @@ -254,7 +199,7 @@ double physics::Vehicle::BatteryDrainSwitchedOff(double dt) const double sn3; double sn4; double sn5; - if (lowVoltage.nominalBatteryVoltage / lowVoltage.batteryVoltage < 1.22) + if (lowVoltage.config.nominalBatteryVoltage / lowVoltage.BatteryVoltage() < 1.22) sn1 = dt * 50; else sn1 = 0; @@ -276,12 +221,12 @@ void physics::Vehicle::MainsCheck(double const Deltatime) { case TPowerSource::CurrentCollector: { - localvoltage = std::max(localvoltage, pantographCircuit.supplyVoltage); + localvoltage = std::max(localvoltage, pantographCircuit.SupplyVoltage()); break; } case TPowerSource::Accumulator: { - localvoltage = std::max(localvoltage, lowVoltage.power24vVoltage); + localvoltage = std::max(localvoltage, lowVoltage.Voltage24v()); break; } default: @@ -295,7 +240,7 @@ void physics::Vehicle::MainsCheck(double const Deltatime) 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 || (lineBreaker.config.pantographsRequireIt && (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable))}; + auto const maincircuitpowersupply{std::abs(localvoltage) > 0.1 || GetTrainsetHighVoltage() > 0.1 || (lineBreaker.config.pantographsRequireIt && (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()))}; // optional automatic circuit start, once the circuit is initialised if (lineBreaker.UpdateInitialisation(maincircuitpowersupply, Deltatime) && lineBreaker.config.start != start_t::manual && false == (lineBreaker.IsClosed() || diesel.startupRequested)) @@ -313,7 +258,7 @@ void physics::Vehicle::MainsCheck(double const Deltatime) void physics::Vehicle::LowVoltagePowerCheck(double const /*Deltatime*/) { - auto const lowvoltagepower{lowVoltage.power24vAvailable || lowVoltage.power110vAvailable}; + auto const lowvoltagepower{lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()}; if (EngineType == TEngineType::ElectricSeriesMotor) { @@ -370,7 +315,7 @@ double physics::Vehicle::LocalPowerVoltage(Coupling const kind) case Coupling::highVoltage: { // heating power sources - if (trainHeating.on) + if (trainHeating.IsOn()) { switch (HeatingPowerSource.SourceType) { @@ -381,7 +326,7 @@ double physics::Vehicle::LocalPowerVoltage(Coupling const kind) } case TPowerSource::CurrentCollector: { - localvoltage = pantographCircuit.supplyVoltage; + localvoltage = pantographCircuit.SupplyVoltage(); break; } case TPowerSource::Main: @@ -409,7 +354,7 @@ double physics::Vehicle::LocalPowerVoltage(Coupling const kind) { if (converter.IsRunning()) { - localvoltage = lowVoltage.nominalBatteryVoltage; + localvoltage = lowVoltage.config.nominalBatteryVoltage; } // TBD, TODO: reduce by current draw? PowerCircuits[1].first = localvoltage; @@ -418,9 +363,9 @@ double physics::Vehicle::LocalPowerVoltage(Coupling const kind) case Coupling::power24v: { - if (lowVoltage.batteryOn) + if (lowVoltage.IsBatteryOn()) { - localvoltage = lowVoltage.batteryVoltage; + localvoltage = lowVoltage.BatteryVoltage(); } // TBD, TODO: reduce by current draw? PowerCircuits[0].first = localvoltage; @@ -463,7 +408,7 @@ void physics::Vehicle::PowerCouplersVoltage(Coupling const kind, double const ab auto const oppositeheatingcoupling{oppositecoupler.CouplingFlag.HasAny(Coupling::heating)}; oppositecouplingispresent = oppositehighvoltagecoupling || oppositeheatingcoupling; - localpowerexportisenabled = oppositehighvoltagecoupling || (oppositeheatingcoupling && localpowersource && trainHeating.on); + localpowerexportisenabled = oppositehighvoltagecoupling || (oppositeheatingcoupling && localpowersource && trainHeating.IsOn()); break; } @@ -568,9 +513,9 @@ void physics::Vehicle::ConverterCheck(double const Timestep) { ConverterSupply supply; supply.lineBreakerClosed = lineBreaker.IsClosed(); - supply.lowVoltage24v = lowVoltage.power24vAvailable; + supply.lowVoltage24v = lowVoltage.Is24vAvailable(); supply.directionActive = DirActive != 0; - supply.pantographPressureLock = pantographAir.pressureLockActive; + supply.pantographPressureLock = pantographAir.IsPressureLockActive(); // HACK: allow carriages to operate converter without (missing) fuse prerequisite supply.highVoltage = Power > 1.0 ? MainCircuitPowered() : GetTrainsetHighVoltage() > 0.0; supply.damaged = TestFlag(EngDmgFlag, 4); @@ -593,7 +538,7 @@ void physics::Vehicle::HeatingCheck(double const /*Timestep*/) generator.revolutions = *generator.engine_revolutions; auto const absrevolutions{std::abs(generator.revolutions)}; - generator.voltage = (false == trainHeating.allow ? 0.0 : + generator.voltage = (false == trainHeating.IsAllowed() ? 0.0 : // TODO: add support for desired voltage selector absrevolutions < generator.revolutions_min ? generator.voltage_min * absrevolutions / generator.revolutions_min : @@ -605,9 +550,9 @@ void physics::Vehicle::HeatingCheck(double const /*Timestep*/) } // quick check first to avoid unnecessary calls... - if (false == trainHeating.allow) + if (false == trainHeating.IsAllowed()) { - trainHeating.on = false; + trainHeating.SetOn(false); return; } // ...detailed check if we're still here @@ -624,7 +569,7 @@ void physics::Vehicle::HeatingCheck(double const /*Timestep*/) } case TPowerSource::CurrentCollector: { - voltage = pantographCircuit.supplyVoltage; + voltage = pantographCircuit.SupplyVoltage(); break; } case TPowerSource::PowerCable: @@ -647,11 +592,11 @@ void physics::Vehicle::HeatingCheck(double const /*Timestep*/) } } - trainHeating.on = voltage > heatingpowerthreshold; + trainHeating.SetOn(voltage > heatingpowerthreshold); - if (trainHeating.on) + if (trainHeating.IsOn()) { - TotalCurrent += 1000 * trainHeating.power / voltage; // heater power cost presumably specified in kilowatts + TotalCurrent += 1000 * trainHeating.config.power / voltage; // heater power cost presumably specified in kilowatts } } @@ -661,7 +606,7 @@ void physics::Vehicle::PantographsCheck(double const /*Timestep*/) { auto const &valve{pantographAir.valve}; - auto const lowvoltagepower{valve.solenoid ? lowVoltage.power24vAvailable || lowVoltage.power110vAvailable : true}; + auto const lowvoltagepower{valve.solenoid ? lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable() : true}; auto const autostart{valve.start_type == automatic || valve.start_type == manualwithautofallback}; auto const manualcontrol{valve.start_type == manual || valve.start_type == manualwithautofallback}; @@ -677,13 +622,13 @@ void physics::Vehicle::PantographsCheck(double const /*Timestep*/) { auto &valve{pantograph.valve}; - auto const lowvoltagepower{valve.solenoid ? lowVoltage.power24vAvailable || lowVoltage.power110vAvailable : true}; + auto const lowvoltagepower{valve.solenoid ? lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable() : true}; auto const autostart{valve.start_type == automatic || valve.start_type == manualwithautofallback}; auto const manualcontrol{valve.start_type == manual || valve.start_type == manualwithautofallback}; valve.is_active = (valve.spring ? lowvoltagepower : true) // spring actuator needs power to maintain non-default state && (manualcontrol && lowvoltagepower ? false == valve.is_disabled : true) // needs power to change state, without it just pass through - && (manualcontrol && lowvoltagepower ? false == pantographCircuit.allDown : true) && + && (manualcontrol && lowvoltagepower ? false == pantographCircuit.AllDown() : true) && (lineBreaker.IsClosed() || false == lineBreaker.config.pantographsRequireIt) // fed through the closed line breaker, where it comes first && (valve.is_active || (manualcontrol && lowvoltagepower && valve.is_enabled) || (autostart && lowvoltagepower)); // shouldn't ever get this far but, eh @@ -705,7 +650,7 @@ void physics::Vehicle::GensetCheck(double const Deltatime) } auto &genset{Genset}; auto const wasactive{genset.is_active}; - auto const lowvoltagepower{lowVoltage.power24vAvailable || lowVoltage.power110vAvailable}; + auto const lowvoltagepower{lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()}; auto const requested{lowvoltagepower && false == genset.is_disabled && (genset.start_type == start_t::automatic ? GensetSelected() : genset.is_enabled)}; if (false == requested) { @@ -759,13 +704,13 @@ void physics::Vehicle::LightsCheck(double const /*Timestep*/) light.is_active = // TODO: bind properly power source when ld is in place - (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) // power source + (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) // power source && false == light.is_disabled && (true == light.is_active || (light.start_type == start_t::manual ? light.is_enabled : true)); light.intensity = (light.is_active ? 1.0f : 0.0f) // TODO: bind properly power source when ld is in place - * (lowVoltage.power110vAvailable ? 1.0f : - lowVoltage.power24vAvailable ? 0.5f : + * (lowVoltage.Is110vAvailable() ? 1.0f : + lowVoltage.Is24vAvailable() ? 0.5f : 0.0f) * light.dimming; } @@ -782,13 +727,10 @@ bool physics::Vehicle::BatterySwitch(bool State, range_t const Notify) // the battery of a vehicle prepared for hauling stays off return false; } - auto const initialstate{lowVoltage.batteryOn}; + auto const initialstate{lowVoltage.IsBatteryOn()}; // Ra: ukrotnienie załączania baterii jest jakąś fikcją... - if (lowVoltage.batteryStart == start_t::manual) - { - lowVoltage.batteryOn = State; - } + lowVoltage.SwitchBattery(State); // switching batteries does not require activation if (Notify != local) @@ -797,7 +739,7 @@ bool physics::Vehicle::BatterySwitch(bool State, range_t const Notify) SendCtrlToNext(VehicleCommand::batterySwitch, State ? 1 : 0, -1, Notify == unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return lowVoltage.batteryOn != initialstate; + return lowVoltage.IsBatteryOn() != initialstate; } bool physics::Vehicle::CompartmentLightsSwitch(bool State, range_t const Notify) @@ -952,7 +894,7 @@ bool physics::Vehicle::ConverterSwitch(bool State, range_t const Notify) bool physics::Vehicle::HeatingSwitch(bool const State, range_t const Notify) { - bool const initialstate{trainHeating.allow}; + bool const initialstate{trainHeating.IsAllowed()}; HeatingSwitch_(State); @@ -963,14 +905,14 @@ bool physics::Vehicle::HeatingSwitch(bool const State, range_t const Notify) SendCtrlToNext(VehicleCommand::heatingSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return trainHeating.allow != initialstate; + return trainHeating.IsAllowed() != initialstate; } void physics::Vehicle::HeatingSwitch_(bool const State) { // TBD, TODO: activation dependencies? - trainHeating.allow = State; + trainHeating.Allow(State); } // the start request of the genset of a dual-mode vehicle; one which starts on its own ignores it, but passes it on to @@ -996,7 +938,7 @@ bool physics::Vehicle::GensetSwitch(bool const State, range_t const Notify) // genset of a dual-mode vehicle double physics::Vehicle::TractionSourceVoltage() const { - return GensetSelected() ? Genset.voltage : pantographCircuit.supplyVoltage; + return GensetSelected() ? Genset.voltage : pantographCircuit.SupplyVoltage(); } // the voltage the traction circuit gets: from the vehicle's own source, or through the train's high voltage line @@ -1035,7 +977,7 @@ double physics::Vehicle::EnginePowerSourceVoltage() const { return EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? TractionSupplyVoltage() : - EnginePowerSource.SourceType == TPowerSource::Accumulator ? lowVoltage.power24vVoltage : + EnginePowerSource.SourceType == TPowerSource::Accumulator ? lowVoltage.Voltage24v() : 0.0; } @@ -1185,9 +1127,9 @@ bool physics::Vehicle::OperatePantographValve(VehicleEnd const End, operation_t bool physics::Vehicle::DropAllPantographs(bool const State, range_t const Notify) { - auto const initialstate{pantographCircuit.allDown}; + auto const initialstate{pantographCircuit.AllDown()}; - pantographCircuit.allDown = State; + pantographCircuit.SetAllDown(State); if (Notify != range_t::local) { @@ -1231,7 +1173,7 @@ double physics::Vehicle::GetTrainsetVoltage(CouplingSet const couplings) const double physics::Vehicle::GetTrainsetHighVoltage() const { - return std::max(GetTrainsetVoltage(Coupling::highVoltage), trainHeating.allow ? GetTrainsetVoltage(Coupling::heating) : 0.0); + return std::max(GetTrainsetVoltage(Coupling::highVoltage), trainHeating.IsAllowed() ? GetTrainsetVoltage(Coupling::heating) : 0.0); } int physics::Vehicle::clampDimmerPosition(int const Position) const diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index 3f7556b72..a4d346bfc 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -62,7 +62,7 @@ void physics::Vehicle::LoadFIZ_Param(std::string const &line) extract_value(Vmax, "Vmax", line, "0"); extract_value(Power, "PWR", line, "0"); extract_value(SandCapacity, "SandCap", line, "0"); - extract_value(trainHeating.power, "HeatingP", line, "0"); + extract_value(trainHeating.config.power, "HeatingP", line, "0"); extract_value(LightPower, "LightP", line, "0"); { @@ -896,9 +896,9 @@ void physics::Vehicle::LoadFIZ_CntrlControllers(std::string const &line) extract_value(isDoubleClickForMeasureNeeded, "DCMB", line, ""); extract_value(DistanceCounterDoublePressPeriod, "DCDPP", line, ""); - extract_value(lowVoltage.batteryButtonImpulse, "IBTB", line, ""); - extract_value(lowVoltage.batteryButtonHeld, "SBBBH", line, ""); - extract_value(lowVoltage.batteryButtonHoldTime, "BBHT", line, ""); + extract_value(lowVoltage.config.batteryButtonImpulse, "IBTB", line, ""); + extract_value(lowVoltage.config.batteryButtonHeld, "SBBBH", line, ""); + extract_value(lowVoltage.config.batteryButtonHoldTime, "BBHT", line, ""); } // Cntrl.: how the devices start (MainStart, BatteryStart, ...) and their relays @@ -921,7 +921,7 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) // battery { auto lookup = starts.find(extract_value("BatteryStart", line)); - lowVoltage.batteryStart = lookup != starts.end() ? lookup->second : manual; + lowVoltage.config.batteryStart = lookup != starts.end() ? lookup->second : manual; } // converter { @@ -938,11 +938,11 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) // pantograph compressor { auto lookup = starts.find(extract_value("PantCompressorStart", line)); - pantographAir.compressorStart = lookup != starts.end() ? lookup->second : manual; + pantographAir.config.compressorStart = lookup != starts.end() ? lookup->second : manual; } // pantograph compressor valve - pantographAir.autoValve = TrainType == train_type::emu; // legacy code behaviour, automatic valve was initially installed in all EMUs - extract_value(pantographAir.autoValve, "PantAutoValve", line, ""); + pantographAir.config.autoValve = TrainType == train_type::emu; // legacy code behaviour, automatic valve was initially installed in all EMUs + extract_value(pantographAir.config.autoValve, "PantAutoValve", line, ""); // pantographs valve { auto lookup = starts.find(extract_value("PantEPValveStart", line)); @@ -1076,8 +1076,9 @@ void physics::Vehicle::LoadFIZ_Light(std::string const &line) LoadFIZ_PowerParamsDecode(AlterLightPowerSource, "AlterL", line); extract_value(NominalVoltage, "Volt", line, ""); - extract_value(lowVoltage.batteryVoltage, "LMaxVoltage", line, ""); - lowVoltage.nominalBatteryVoltage = static_cast(lowVoltage.batteryVoltage); + auto batteryvoltage{lowVoltage.BatteryVoltage()}; + extract_value(batteryvoltage, "LMaxVoltage", line, ""); + lowVoltage.SetBattery(batteryvoltage); } void physics::Vehicle::LoadFIZ_Clima(std::string const &line) @@ -1368,7 +1369,7 @@ void physics::Vehicle::LoadFIZ_EngineDieselElectric(std::string const &Input) ImaxHi = 2; ImaxLo = 1; } - extract_value(trainHeating.engineRpm, "HeatingRPM", Input, ""); + extract_value(trainHeating.config.engineRpm, "HeatingRPM", Input, ""); extract_value(diesel.shaftInertia, "AIM", Input, "1.25"); extract_value(diesel.revolutionsDecreaseRate, "RPMDecRate", Input, ""); LoadFIZ_DieselElectricDynamicBrake(Input); @@ -1468,12 +1469,12 @@ void physics::Vehicle::LoadFIZ_EngineDieselShared(std::string const &Input) void physics::Vehicle::LoadFIZ_Switches(std::string const &Input) { - extract_value(pantographCircuit.switchType, "Pantograph", Input, ""); + extract_value(pantographCircuit.config.switchType, "Pantograph", Input, ""); extract_value(converter.config.switchType, "Converter", Input, ""); extract_value(lineContactors.config.switchType, "MotorConnectors", Input, ""); - trainHeating.switchImpulse = ToLower(extract_value("TrainHeating", Input)) == "impulse"; + trainHeating.config.switchImpulse = ToLower(extract_value("TrainHeating", Input)) == "impulse"; // because people can't make up their minds whether it's "impulse" or "Impulse"... - pantographCircuit.switchType = ToLower(pantographCircuit.switchType); + pantographCircuit.config.switchType = ToLower(pantographCircuit.config.switchType); converter.config.switchType = ToLower(converter.config.switchType); lineContactors.config.switchType = ToLower(lineContactors.config.switchType); // universal reset buttons assignments diff --git a/physics/components/lowvoltage.h b/physics/components/lowvoltage.h index 5127e3455..0709d8101 100644 --- a/physics/components/lowvoltage.h +++ b/physics/components/lowvoltage.h @@ -7,7 +7,8 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the low voltage supply and the train heating of a vehicle, held by physics::Vehicle as lowVoltage and trainHeating +// the low voltage supply and the train heating of a vehicle, held by physics::Vehicle as lowVoltage and trainHeating. +// as the parts of the main circuit (maincircuit.h): the definition in `config`, the state behind queries and operations #pragma once @@ -17,30 +18,112 @@ namespace physics { // the battery and the low voltage circuits -struct LowVoltageSupply +class LowVoltageSupply { - bool batteryOn = false; // the battery switched on - double batteryVoltage = 0.0; - float nominalBatteryVoltage = 0.f; - start_t batteryStart = start_t::manual; - bool power110vAvailable = false; // the 110 V circuit has power, as the last step found it - bool power24vAvailable = false; // the 24 V circuit has power, as the last step found it - double power24vVoltage{0.0}; // the voltage of the battery circuit, as the last step found it - // the battery switch of the cab - bool batteryButtonFired = false; // the button already pressed - bool batteryButtonImpulse = false; // the switch works as a single button - bool batteryButtonHeld = false; // the button has to be held to switch the battery on or off - float batteryButtonHoldTime = 1.f; // how long it has to be held [s] + public: + struct Config + { + float nominalBatteryVoltage{0.f}; + start_t batteryStart{start_t::manual}; + // the battery switch of the cab + bool batteryButtonImpulse{false}; // the switch works as a single button + bool batteryButtonHeld{false}; // the button has to be held to switch the battery on or off + float batteryButtonHoldTime{1.f}; // how long it has to be held [s] + }; + Config config; + + // the battery of the definition (LMaxVoltage), charged + void SetBattery(double const Voltage) + { + batteryVoltage = Voltage; + config.nominalBatteryVoltage = static_cast(Voltage); + } + + bool IsBatteryOn() const { return batteryOn; } + // the battery switch, where the battery is switched by hand; returns whether that changed it + bool SwitchBattery(bool const State) + { + auto const initialstate{batteryOn}; + if (config.batteryStart == start_t::manual) + { + batteryOn = State; + } + return batteryOn != initialstate; + } + // the battery cut off whatever its switch, as for a vehicle prepared for hauling + void DisconnectBattery() { batteryOn = false; } + // the battery as the vehicle is placed: on, unless the vehicle has none + void ResetBattery() { batteryOn = config.batteryStart != start_t::disabled; } + // for the tests: the battery on or off, whatever its switch + void SetBatteryOnForTest(bool const State) { batteryOn = State; } + + double BatteryVoltage() const { return batteryVoltage; } + // the battery drained by the given amount [V]; returns whether its voltage fell too low for the line breaker to hold. + // it neither charges above its nominal voltage nor drops to nothing + bool DrainBattery(double const Drain) + { + batteryVoltage -= Drain; + auto const toolow{config.nominalBatteryVoltage / batteryVoltage > 1.57}; + if (batteryVoltage > config.nominalBatteryVoltage) + { + batteryVoltage = config.nominalBatteryVoltage; // wstrzymanie ładowania pow. 110V + } + if (batteryVoltage < 0.01) + { + batteryVoltage = 0.01; + } + return toolow; + } + // the battery kept at its nominal voltage, where its drain isn't modelled + void KeepBatteryCharged() { batteryVoltage = config.nominalBatteryVoltage; } + + // the low voltage circuits, as the last step found them + bool const &Is24vAvailable() const { return power24vAvailable; } + bool const &Is110vAvailable() const { return power110vAvailable; } + // either of them + bool IsAvailable() const { return power24vAvailable || power110vAvailable; } + // the voltage of the battery circuit + double Voltage24v() const { return power24vVoltage; } + // the circuits in the step: the 24 V one from its voltage, the 110 V one as given + void SetSupply(double const Voltage24v, bool const Available110v) + { + power24vVoltage = Voltage24v; + power24vAvailable = power24vVoltage > 0; + power110vAvailable = Available110v; + } + // for the tests of the parts the circuits feed: the power of a circuit as given, whatever the voltage + void Set24vAvailableForTest(bool const State) { power24vAvailable = State; } + void Set110vAvailableForTest(bool const State) { power110vAvailable = State; } + + private: + bool batteryOn{false}; + double batteryVoltage{0.0}; + bool power110vAvailable{false}; + bool power24vAvailable{false}; + double power24vVoltage{0.0}; }; // the heating of the train fed by the vehicle -struct TrainHeating +class TrainHeating { - bool on = false; - bool allow{false}; // the heating switch. TODO: wrap the heating in a basic device - bool switchImpulse{false}; // the switch springs back to its middle position - double power = 0.0; - double engineRpm{0.0}; // the revolutions of the engine guaranteed with the heating on + public: + struct Config + { + bool switchImpulse{false}; // the switch springs back to its middle position + double power{0.0}; + double engineRpm{0.0}; // the revolutions of the engine guaranteed with the heating on + }; + Config config; + + bool IsOn() const { return on; } + void SetOn(bool const State) { on = State; } + // the heating switch. TODO: wrap the heating in a basic device + bool IsAllowed() const { return allow; } + void Allow(bool const State) { allow = State; } + + private: + bool on{false}; + bool allow{false}; }; } // namespace physics diff --git a/physics/components/pantographs.h b/physics/components/pantographs.h index e4ee98505..4e406593a 100644 --- a/physics/components/pantographs.h +++ b/physics/components/pantographs.h @@ -8,10 +8,12 @@ http://mozilla.org/MPL/2.0/. */ // the circuit and the air of the pantographs of a vehicle, held by physics::Vehicle as pantographCircuit and -// pantographAir beside its pantographs +// pantographAir beside its pantographs. as the parts of the main circuit (maincircuit.h): the definition in `config`, the +// state behind queries and operations #pragma once +#include #include #include @@ -21,30 +23,191 @@ namespace physics { // the circuit of the pantographs: their voltages, the kind of their switches, the presets of the cabs -struct PantographCircuit +class PantographCircuit { - double frontVoltage = 0.0; // the voltage at the front pantograph - double rearVoltage = 0.0; // the voltage at the rear one - double supplyVoltage{0.0}; // the voltage supplied to the pantographs - bool allDown{false}; // the switch that lowers all of them - std::string switchType; // PantSwitchType: the kind of the switches of the cab + public: + struct Config + { + std::string switchType; // PantSwitchType: the kind of the switches of the cab + }; + Config config; + + // the voltage at the pantograph of the given end, from the overhead line it touches + double Voltage(VehicleEnd const End) const { return End == VehicleEnd::front ? frontVoltage : rearVoltage; } + double FrontVoltage() const { return frontVoltage; } + double RearVoltage() const { return rearVoltage; } + void SetFrontVoltage(double const Voltage) { frontVoltage = Voltage; } + void SetRearVoltage(double const Voltage) { rearVoltage = Voltage; } + // the voltage supplied to the pantographs, from the overhead line the vehicle is under + double SupplyVoltage() const { return supplyVoltage; } + void SetSupplyVoltage(double const Voltage) { supplyVoltage = Voltage; } + + // the switch that lowers all of them + bool AllDown() const { return allDown; } + void SetAllDown(bool const State) { allDown = State; } + // the presets of the pantographs: the setups they can be switched to as chars, and the one selected in each cab std::pair> presets{"0132", {0, 0}}; + + private: + double frontVoltage{0.0}; + double rearVoltage{0.0}; + double supplyVoltage{0.0}; + bool allDown{false}; +}; + +// what the air of the pantographs needs to know in the step +struct PantographAirSupply +{ + bool anyPantographActive{false}; // a pantograph of the vehicle is up or rising + bool lowVoltage{false}; // the low voltage circuits have their power + bool collectors{false}; // the vehicle takes its power through pantographs: they have air of their own + bool multipleUnit{false}; // an electric multiple unit: its small compressor fills slower, its pressure switch locks + double mainReservoirPressure{0.0}; // [bar] + double controlReservoirPressure{0.0}; // [bar], what the gauge shows on a vehicle of no pantographs + double maxPressure{0.0}; // of the pantographs [bar], CollectorParameters.MaxPress + double minPressure{0.0}; // below which the pressure switch trips [bar], CollectorParameters.MinPress }; // the air of the pantographs: their reservoir, the small compressor that fills it, the valves -struct PantographAir +class PantographAir { - double volume = 0.48; // so that the raised pantographs drop soon with the compressor off - double pressure = 0.0; // in the reservoirs of the pantographs - bool compressorRunning = false; // the small compressor - start_t compressorStart{start_t::manual}; // PantCompressorStart - int compressorPower = 0; // SmallCompressorPower + public: + struct Config + { + start_t compressorStart{start_t::manual}; // PantCompressorStart + int compressorPower{0}; // SmallCompressorPower + bool autoValve{false}; // the kind of the valve of the small compressor fitted + }; + Config config; + basic_valve valve; - bool connectedToMainReservoir = true; // the three-way cock: to the main reservoir, or to the small compressor - bool autoValve{false}; // the kind of the valve of the small compressor fitted - bool pressureSwitchActive{false}; // the pressure switch, primed at the pressure set in the air of the pantographs - bool pressureLockActive{false}; // fires when the pressure switch trips by the pressure dropping below its level + + // in the reservoirs of the pantographs [bar] + double const &Pressure() const { return pressure; } + // the air in them, in the units of the model of their reservoir + double Volume() const { return volume; } + // the reservoirs of a vehicle placed with its pantographs down and empty + void Empty() + { + volume = 0.1; + pressure = 0.0; + } + + // the small compressor + bool IsCompressorRunning() const { return compressorRunning; } + void SwitchCompressor(bool const State) { compressorRunning = State; } + // the three-way cock: to the main reservoir, or to the small compressor + bool IsConnectedToMainReservoir() const { return connectedToMainReservoir; } + void ConnectToMainReservoir(bool const State) { connectedToMainReservoir = State; } + + // the pressure switch, primed at the pressure set in the air of the pantographs + bool IsPressureSwitchPrimed() const { return pressureSwitchActive; } + // the lock of the converter and the heating of a multiple unit, set when the pressure switch trips + bool IsPressureLockActive() const { return pressureLockActive; } + + // the step of the air of the pantographs. returns whether the pressure switch tripped in it, by the pressure falling + // below its level: the switch is spent then, and the lock of a multiple unit set; what else follows is up to the vehicle + bool Update(PantographAirSupply const &Supply, double const dt) + { + // automatic start if the pressure is too low + compressorRunning |= pressure < 4.2 && Supply.anyPantographActive && (config.compressorStart == start_t::automatic || config.compressorStart == start_t::manualwithautofallback); + compressorRunning &= Supply.lowVoltage; + + if (false == Supply.collectors) + { + // a tu coś dla SM42 i SM31, aby pokazywać na manometrze + pressure = Supply.controlReservoirPressure; + return false; + } + // Ra 2014-07: zasadniczo, to istnieje zbiornik rozrządu i zbiornik pantografów - na razie mamy razem + // Ra 2014-07: kurek trójdrogowy łączy spr.pom. z pantografami i wyłącznikiem ciśnieniowym WS + // Ra 2014-07: zbiornika rozrządu nie pompuje się tu, tylko pantografy; potem można zamknąć + // WS i odpalić resztę + if (config.autoValve ? pressure < Supply.mainReservoirPressure : connectedToMainReservoir) // kurek zamyka połączenie z ZG + { + // zbiornik pantografu połączony ze zbiornikiem głównym - małą sprężarką się tego nie napompuje + // Ra 2013-12: Niebugocław mówi, że w EZT nie ma potrzeby odcinać kurkiem + // ograniczenie ciśnienia do MaxPress (tylko w pantografach!) + // (the bounds as the .fiz gives them, which may cross) + pressure = std::min(std::max(Supply.mainReservoirPressure, 0.0), Supply.maxPressure); + volume = (pressure + 1.0) * 0.1; // objętość, na wypadek odcięcia kurkiem + } + else + { + // zbiornik główny odcięty, można pompować pantografy + if (compressorRunning) + { + // włączona mała sprężarka + volume += dt + // Ra 2013-12: Niebugocław mówi, że w EZT nabija 1.5 raz wolniej niż jak było 0.005 + * (Supply.multipleUnit ? 0.003 : 0.005) / std::max(1.0, pressure) * (0.45 - (0.1 / volume / 10 - 0.1)) / 0.45; + } + pressure = std::min(std::max(10.0 * volume - 1.0, 0.0), Supply.maxPressure); // tu by się przydała objętość zbiornika + } + if (false == compressorRunning && volume > 0.1) + { + volume -= dt * 0.0003 * std::max(1.0, pressure * 0.5); // nieszczelności: 0.0003=0.3l/s + } + return UpdatePressureSwitch(Supply); + } + + // the pressure switch: low, it trips once (see Update()); primed again over 4.6 bar, where the small compressor stops + // at 4.8. returns whether it tripped + bool UpdatePressureSwitch(PantographAirSupply const &Supply) + { + if (pressure < Supply.minPressure) + { + // 3.5 wg http://www.transportszynowy.pl/eu06-07pneumat.php + if (false == pressureSwitchActive) + { + return false; + } + // specialized variant for EMU -- pwr system disables converter and heating, + // and prevents their activation until pressure switch is set again + if (Supply.multipleUnit) + { + pressureLockActive = true; + } + // mark the pressure switch as spent + pressureSwitchActive = false; + return true; + } + if (pressure >= 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 (Supply.lowVoltage) + { + // prime the pressure switch + pressureSwitchActive = true; + // turn off the subsystems lock + pressureLockActive = false; + } + if (pressure >= 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) + compressorRunning = false; + } + } + return false; + } + + // for the tests: the reservoirs at the given pressure, with the pressure switch primed or not + void SetForTest(double const Pressure, bool const PressureSwitchPrimed) + { + pressure = Pressure; + pressureSwitchActive = PressureSwitchPrimed; + } + + private: + double volume{0.48}; // so that the raised pantographs drop soon with the compressor off + double pressure{0.0}; + bool compressorRunning{false}; + bool connectedToMainReservoir{true}; + bool pressureSwitchActive{false}; + bool pressureLockActive{false}; }; } // namespace physics diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 886ce0cd7..4156ec35e 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -246,7 +246,7 @@ bool physics::Vehicle::EpFuseSwitch(bool State) // ************************************************************************************************* bool physics::Vehicle::SpringBrakeActivate(bool State) { - if (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) + if (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) { SendCtrlToNext(VehicleCommand::springBrakeActivate, int(State), CabActive, CouplingSet::FromBits(brakes.spring.controlCouplings)); @@ -541,7 +541,7 @@ bool physics::Vehicle::UniversalBrakeButton(int button, int state) bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 brakes.universalButtonPressed[button] = state > 0; int flag = 0; - if (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable) + if (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) { for (int i = 0; i < 3; i++) { @@ -588,7 +588,7 @@ bool physics::Vehicle::SwitchEPBrake(int state) bool physics::Vehicle::EPBrakeControlPowered() const { - return lowVoltage.power24vAvailable && DirActive != 0 && EpFuse; + return lowVoltage.Is24vAvailable() && DirActive != 0 && EpFuse; } // ************************************************************************************************* @@ -810,7 +810,7 @@ void physics::Vehicle::CompressorCheck(double dt) } // the main circuit, also for a compressor driven by the engine, otherwise the low voltage - auto const compressorpower{air.compressor.supply == CompressorSupply::mainCircuit || air.compressor.supply == CompressorSupply::engine ? MainCircuitPowered() : lowVoltage.power110vAvailable}; + auto const compressorpower{air.compressor.supply == CompressorSupply::mainCircuit || air.compressor.supply == CompressorSupply::engine ? MainCircuitPowered() : lowVoltage.Is110vAvailable()}; air.compressor.powerTime = compressorpower ? air.compressor.powerTime + dt : 0.0; auto const compressorready{compressorpower && air.compressor.powerTime >= air.compressor.startDelay}; // TBD: split CompressorAllow into separate enable/disable flags, inherit compressor from basic_device @@ -1226,7 +1226,7 @@ void physics::Vehicle::UpdateEPBrake() else EpForce = 0.0; - brakes.electrodynamic.emuWorking = EpForce > 0.001 ? lowVoltage.power110vAvailable : true; + brakes.electrodynamic.emuWorking = EpForce > 0.001 ? lowVoltage.Is110vAvailable() : true; double temp1 = EpForce; if (brakes.emuDynamic.epMaxSpeed > 0.001 && Vel > brakes.emuDynamic.epMaxSpeed && brakes.electrodynamic.emuWorking) diff --git a/physics/components/securitysystem.cpp b/physics/components/securitysystem.cpp index 5d1fdf2e6..3671c0b4b 100644 --- a/physics/components/securitysystem.cpp +++ b/physics/components/securitysystem.cpp @@ -248,12 +248,12 @@ void physics::Vehicle::SecuritySystemReset(void) // zbijanie czuwaka/SHP // ************************************************************************************************* void physics::Vehicle::SecuritySystemCheck(double dt) { - bool isPower = lowVoltage.power24vAvailable || lowVoltage.power110vAvailable; + bool isPower = lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable(); // the shunt mode of the SM42 switches its vigilance device (CA) off, on the vehicles with AwareOffInShuntMode=Yes (eu07/maszyna#457) SecuritySystem.set_shunt_mode(ShuntMode); SecuritySystem.update(dt, Vel, isPower, CabActive); - if (!lowVoltage.batteryOn || !Radio || !RadioFuse) + if (!lowVoltage.IsBatteryOn() || !Radio || !RadioFuse) { // wyłączenie baterii deaktywuje sprzęt RadiostopSwitch(false); } diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index 128047d35..ff2d4fe0e 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -41,9 +41,9 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) AutoRelayFlag = AutoRelayType == 1; - if (lowVoltage.nominalBatteryVoltage == 0.0) + if (lowVoltage.config.nominalBatteryVoltage == 0.0) { - lowVoltage.batteryStart = start_t::disabled; + lowVoltage.config.batteryStart = start_t::disabled; } Sand = SandCapacity; @@ -111,7 +111,7 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) { HeatingPowerSource.SourceType = TPowerSource::Main; } - if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && trainHeating.power > 0) + if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && trainHeating.config.power > 0) { HeatingPowerSource.SourceType = TPowerSource::PowerCable; HeatingPowerSource.PowerType = TPowerType::ElectricPower; @@ -441,7 +441,7 @@ void physics::Vehicle::SetReadyToDepart() DirAbsolute = DirActive * CabActive; // kierunek jazdy względem sprzęgów brakes.pipeLimiterPressure = brakes.controlReservoirPressure; - lowVoltage.batteryOn = lowVoltage.batteryStart != start_t::disabled; + lowVoltage.ResetBattery(); } // the air and the brakes of a vehicle standing braked diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index 0feef1456..d00ea4a37 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -97,7 +97,7 @@ double physics::Vehicle::Current(double n, double U) } } - if (brakes.electrodynamic.on && !FuseFlag && brakes.electrodynamic.type == dbrake_automatic && lowVoltage.power110vAvailable && lineBreaker.IsClosed()) // hamowanie EP09 //TUHEX + if (brakes.electrodynamic.on && !FuseFlag && brakes.electrodynamic.type == dbrake_automatic && lowVoltage.Is110vAvailable() && lineBreaker.IsClosed()) // hamowanie EP09 //TUHEX { // TODO: zrobic bardziej uniwersalne nie tylko dla EP09 MotorCurrent = -std::max(motor_param(0).fi * (Vadd / (Vadd + motor_param(0).Isat) - motor_param(0).fi0), 0.) * n * 2.0 / brakes.electrodynamic.resistance; @@ -139,11 +139,11 @@ void physics::Vehicle::UpdateSeriesMotorDynamicBrakeFlag() brakes.electrodynamic.on = false; else if (brakes.cylinderPressure > 0.25 && brakes.distributor->GetEDBCP() > 0.25) brakes.electrodynamic.on = true; - brakes.electrodynamic.on = brakes.electrodynamic.on && lowVoltage.power110vAvailable; + brakes.electrodynamic.on = brakes.electrodynamic.on && lowVoltage.Is110vAvailable(); } if (brakes.electrodynamic.type == dbrake_automatic && TrainType == train_type::emu) { - brakes.electrodynamic.on = lowVoltage.power110vAvailable && (TUHEX_Active || Vadd > TUHEX_MinIw) && brakes.electrodynamic.emuWorking; + brakes.electrodynamic.on = lowVoltage.Is110vAvailable() && (TUHEX_Active || Vadd > TUHEX_MinIw) && brakes.electrodynamic.emuWorking; } // wylacznik cisnieniowy yBARC - to jest chyba niepotrzebne tutaj Q: no to usuwam... @@ -381,9 +381,9 @@ bool physics::Vehicle::MotorBlowerPowerIsAvailable(cooling_fan const &Blower) co switch (Blower.start_type) { case start_t::battery: - return lowVoltage.power24vAvailable; + return lowVoltage.Is24vAvailable(); case start_t::converter: - return lowVoltage.power110vAvailable; + return lowVoltage.Is110vAvailable(); default: return MainCircuitPowered(); } @@ -1437,7 +1437,7 @@ void physics::Vehicle::FuseOff(void) bool physics::Vehicle::UniversalResetButton(int const Button, range_t const Notify) { - if (auto const lowvoltagepower{lowVoltage.power24vAvailable || lowVoltage.power110vAvailable}; false == lowvoltagepower) + if (auto const lowvoltagepower{lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()}; false == lowvoltagepower) { return false; } @@ -1457,7 +1457,7 @@ bool physics::Vehicle::UniversalResetButton(int const Button, range_t const Noti bool physics::Vehicle::RelayReset(int const Relays, range_t const Notify) { - auto const lowvoltagepower{lowVoltage.power24vAvailable || lowVoltage.power110vAvailable}; + auto const lowvoltagepower{lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()}; bool reset{false}; if (TestFlag(Relays, relay_t::maincircuitground) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && diff --git a/physics/vehicle.h b/physics/vehicle.h index 2cc62bc21..ba263d896 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -1416,6 +1416,8 @@ class Vehicle void UpdatePantVolume(double dt); // Ra void PantPressureSwitchCheck(); void PantPressureSwitchTrip(); + // what the air of the pantographs needs to know in the step + PantographAirSupply PantographAirSupplyNow() const; void UpdateScndPipePressure(double dt); void UpdateSpringBrake(double dt); double GetDVc(double dt); @@ -1578,7 +1580,7 @@ class Vehicle // whether the radio is switched on, its power supply isn't cut off and it has the low voltage to work bool RadioPowered() const { - return Radio && RadioFuse && (lowVoltage.power24vAvailable || lowVoltage.power110vAvailable); + return Radio && RadioFuse && (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()); } /*obrot kol uwzgledniajacy poslizg*/ double ComputeRotatingWheel(double WForce, double dt, double n) const; diff --git a/rendering/lightarray.cpp b/rendering/lightarray.cpp index 33c5415f4..01ff98ee0 100644 --- a/rendering/lightarray.cpp +++ b/rendering/lightarray.cpp @@ -52,8 +52,8 @@ light_array::update() { light.direction.z = -light.direction.z; } // determine intensity of this light set - if( ( true == light.owner->physics->lowVoltage.power24vAvailable ) - || ( true == light.owner->physics->lowVoltage.power110vAvailable ) ) { + if( ( true == light.owner->physics->lowVoltage.Is24vAvailable() ) + || ( true == light.owner->physics->lowVoltage.Is110vAvailable() ) ) { // with power on, the intensity depends on the state of activated switches // first we cross-check the list of enabled lights with the lights installed in the vehicle... auto const lights { light.owner->physics->iLights[ light.index ] & light.owner->LightList( static_cast( light.index ) ) }; diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 568e8ba97..ac38229b6 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -73,13 +73,13 @@ blackbox::driver driver_of(TDynamicObject const &Vehicle) { std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle const &Controlling) { namespace device = blackbox::cab_devices; auto const on{[](bool const State, std::uint32_t const Bit) { return State ? Bit : 0u; }}; - return on(Occupied.lowVoltage.batteryOn || Controlling.lowVoltage.batteryOn, device::battery) | on(Controlling.lineBreaker.IsClosed(), device::main_breaker) | + return on(Occupied.lowVoltage.IsBatteryOn() || Controlling.lowVoltage.IsBatteryOn(), device::battery) | on(Controlling.lineBreaker.IsClosed(), device::main_breaker) | on(Controlling.pantographs[VehicleEnd::front].is_active, device::pantograph_front) | on(Controlling.pantographs[VehicleEnd::rear].is_active, device::pantograph_rear) | on(Controlling.converter.IsRunning(), device::converter) | on(Controlling.air.compressor.running, device::compressor) | on(Controlling.lineContactors.IsClosed(), device::line_contactors) | on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose, device::sanding) | on(Occupied.WarningSignal != 0, device::horn) | on(false == Occupied.Doors.instances[VehicleSide::left].is_closed, device::doors_left) | on(false == Occupied.Doors.instances[VehicleSide::right].is_closed, device::doors_right) | on(Occupied.Radio, device::radio) | - on(Controlling.trainHeating.on, device::heating) | on(Occupied.brakes.spring.isActive, device::spring_brake) | on(Controlling.ShuntMode, device::shunt_mode) | + on(Controlling.trainHeating.IsOn(), device::heating) | on(Occupied.brakes.spring.isActive, device::spring_brake) | on(Controlling.ShuntMode, device::shunt_mode) | // the doors as the cab works them: the permits, the departure signal, the steps and the lock on(Occupied.DepartureSignal, device::departure_signal) | on(Occupied.Doors.instances[VehicleSide::left].open_permit, device::door_permit_left) | on(Occupied.Doors.instances[VehicleSide::right].open_permit, device::door_permit_right) | on(Occupied.Doors.step_enabled, device::door_step) | diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index dbba5d1d5..a76beee6a 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -108,14 +108,14 @@ void prepare_diesel(driven const &Driven) { // the pantographs' own air topped up by their compressor, and the pantographs raised void raise_pantographs(driven const &Driven) { auto &pantographs{Driven.pantographs}; - if (auto const enough{(pantographs.TrainType == train_type::emu ? 2.5 : 3.5) + 0.1}; pantographs.pantographAir.pressure < enough) { - if (false == pantographs.pantographAir.autoValve) { - pantographs.pantographAir.connectedToMainReservoir = false; // the pantographs on their own air + if (auto const enough{(pantographs.TrainType == train_type::emu ? 2.5 : 3.5) + 0.1}; pantographs.pantographAir.Pressure() < enough) { + if (false == pantographs.pantographAir.config.autoValve) { + pantographs.pantographAir.ConnectToMainReservoir(false); // the pantographs on their own air } - pantographs.pantographAir.compressorRunning = true; + pantographs.pantographAir.SwitchCompressor(true); } - else if (false == pantographs.pantographAir.connectedToMainReservoir || pantographs.pantographAir.pressure <= pantographs.mainPipe.pressure) { - pantographs.pantographAir.compressorRunning = false; + else if (false == pantographs.pantographAir.IsConnectedToMainReservoir() || pantographs.pantographAir.Pressure() <= pantographs.mainPipe.pressure) { + pantographs.pantographAir.SwitchCompressor(false); } Driven.cab.OperatePantographsValve(operation_t::enable); Driven.cab.OperatePantographValve(VehicleEnd::rear, operation_t::enable); @@ -184,7 +184,7 @@ bool start_up(driven Driven, track const &Track, double Seconds, trace *Trace) { if (collector) { raise_pantographs(Driven); } - if (false == collector || std::max(controlling.GetTrainsetHighVoltage(), controlling.pantographCircuit.supplyVoltage) > controlling.EnginePowerSource.CollectorParameters.MinV) { + if (false == collector || std::max(controlling.GetTrainsetHighVoltage(), controlling.pantographCircuit.SupplyVoltage()) > controlling.EnginePowerSource.CollectorParameters.MinV) { // a direction first, as in TController::PrepareDirection(): the relays reset only with one set for (int i = 0; i < 3 && cab.DirActive <= 0; ++i) { cab.DirectionForward(); diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index e252ff90f..21db64dd4 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -133,9 +133,9 @@ std::vector parameters() { {"TotalMass", [](auto const &M) { return M.TotalMass; }}, {"Mred", [](auto const &M) { return M.Mred; }}, {"Power", [](auto const &M) { return M.Power; }}, - {"HeatingPower", [](auto const &M) { return M.trainHeating.power; }}, + {"HeatingPower", [](auto const &M) { return M.trainHeating.config.power; }}, {"LightPower", [](auto const &M) { return M.LightPower; }}, - {"BatteryVoltage", [](auto const &M) { return M.lowVoltage.batteryVoltage; }}, + {"BatteryVoltage", [](auto const &M) { return M.lowVoltage.BatteryVoltage(); }}, {"Cx", [](auto const &M) { return M.Cx; }}, {"WheelDiameter", [](auto const &M) { return M.WheelDiameter; }}, {"TrackW", [](auto const &M) { return M.TrackW; }}, @@ -189,7 +189,7 @@ std::vector parameters() { {"Imax", [](auto const &M) { return M.Imax; }}, {"EIMCtrlType", [](auto const &M) { return M.EIMCtrlType; }}, {"Volume", [](auto const &M) { return M.brakes.reservoirAir; }}, - {"PantVolume", [](auto const &M) { return M.pantographAir.volume; }}, + {"PantVolume", [](auto const &M) { return M.pantographAir.Volume(); }}, }; for (int i = 0; i < 5; ++i) { result.emplace_back(std::format("MaxBrakePress{}", i), [i](auto const &M) { return M.brakes.maxCylinderPressure[i]; }); diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index f85c88105..c2ea5f029 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -42,13 +42,13 @@ std::vector const &invariants() { {"every value a number", [](auto const &M, double, auto const *) { std::initializer_list const values{M.V, M.AccS, M.Ft, M.Fb, M.Im, M.Itot, M.EngineVoltage, - M.enrot, M.brakePipe.pressure, M.brakes.cylinderPressure, M.brakes.independentCylinderPressure, M.mainPipe.pressure, M.air.mainReservoirPressure, M.lowVoltage.batteryVoltage}; + M.enrot, M.brakePipe.pressure, M.brakes.cylinderPressure, M.brakes.independentCylinderPressure, M.mainPipe.pressure, M.air.mainReservoirPressure, M.lowVoltage.BatteryVoltage()}; return std::ranges::all_of(values, [](double const Value) { return std::isfinite(Value); }); }, [](auto const &M) { return values({{"V", M.V}, {"AccS", M.AccS}, {"Ft", M.Ft}, {"Fb", M.Fb}, {"Im", M.Im}, {"Itot", M.Itot}, {"EngineVoltage", M.EngineVoltage}, {"enrot", M.enrot}, {"PipePress", M.brakePipe.pressure}, {"BrakePress", M.brakes.cylinderPressure}, {"LocBrakePress", M.brakes.independentCylinderPressure}, - {"ScndPipePress", M.mainPipe.pressure}, {"Compressor", M.air.mainReservoirPressure}, {"BatteryVoltage", M.lowVoltage.batteryVoltage}}); + {"ScndPipePress", M.mainPipe.pressure}, {"Compressor", M.air.mainReservoirPressure}, {"BatteryVoltage", M.lowVoltage.BatteryVoltage()}}); }}, {"brake cylinders between empty and the vehicle's highest pressure", [](auto const &M, double, auto const *) { @@ -93,8 +93,8 @@ std::vector const &invariants() { }, [](auto const &M) { return values({{"enrot", M.enrot}, {"dizel_nmax", M.diesel.maxRevolutions}}); }}, {"battery no higher than its nominal voltage", - [](auto const &M, double, auto const *) { return M.lowVoltage.nominalBatteryVoltage <= 0.0 || M.lowVoltage.batteryVoltage <= 1.05 * M.lowVoltage.nominalBatteryVoltage; }, - [](auto const &M) { return values({{"BatteryVoltage", M.lowVoltage.batteryVoltage}, {"NominalBatteryVoltage", M.lowVoltage.nominalBatteryVoltage}}); }}, + [](auto const &M, double, auto const *) { return M.lowVoltage.config.nominalBatteryVoltage <= 0.0 || M.lowVoltage.BatteryVoltage() <= 1.05 * M.lowVoltage.config.nominalBatteryVoltage; }, + [](auto const &M) { return values({{"BatteryVoltage", M.lowVoltage.BatteryVoltage()}, {"NominalBatteryVoltage", M.lowVoltage.config.nominalBatteryVoltage}}); }}, {"distance counted as the speed runs", [](auto const &M, double Time, auto const *Before) { if (Before == nullptr) { diff --git a/tests/unit/test_auxiliaries.cpp b/tests/unit/test_auxiliaries.cpp index 5df40fd95..c8ca48ed2 100644 --- a/tests/unit/test_auxiliaries.cpp +++ b/tests/unit/test_auxiliaries.cpp @@ -14,15 +14,15 @@ namespace { std::vector auxiliaries() { return { - {"BatteryVoltage", [](auto const &M) { return M.lowVoltage.batteryVoltage; }}, - {"Battery", [](auto const &M) { return M.lowVoltage.batteryOn ? 1.0 : 0.0; }}, + {"BatteryVoltage", [](auto const &M) { return M.lowVoltage.BatteryVoltage(); }}, + {"Battery", [](auto const &M) { return M.lowVoltage.IsBatteryOn() ? 1.0 : 0.0; }}, {"ConverterFlag", [](auto const &M) { return M.converter.IsRunning() ? 1.0 : 0.0; }}, - {"Power110vIsAvailable", [](auto const &M) { return M.lowVoltage.power110vAvailable ? 1.0 : 0.0; }}, - {"PantPress", [](auto const &M) { return M.pantographAir.pressure; }}, - {"PantVolume", [](auto const &M) { return M.pantographAir.volume; }}, - {"PantCompFlag", [](auto const &M) { return M.pantographAir.compressorRunning ? 1.0 : 0.0; }}, - {"PantPressSwitchActive", [](auto const &M) { return M.pantographAir.pressureSwitchActive ? 1.0 : 0.0; }}, - {"PantPressLockActive", [](auto const &M) { return M.pantographAir.pressureLockActive ? 1.0 : 0.0; }}, + {"Power110vIsAvailable", [](auto const &M) { return M.lowVoltage.Is110vAvailable() ? 1.0 : 0.0; }}, + {"PantPress", [](auto const &M) { return M.pantographAir.Pressure(); }}, + {"PantVolume", [](auto const &M) { return M.pantographAir.Volume(); }}, + {"PantCompFlag", [](auto const &M) { return M.pantographAir.IsCompressorRunning() ? 1.0 : 0.0; }}, + {"PantPressSwitchActive", [](auto const &M) { return M.pantographAir.IsPressureSwitchPrimed() ? 1.0 : 0.0; }}, + {"PantPressLockActive", [](auto const &M) { return M.pantographAir.IsPressureLockActive() ? 1.0 : 0.0; }}, }; } @@ -35,21 +35,21 @@ TEST_CASE("auxiliaries: the battery drained by the lights and the pantographs' c scenario.add("4e_v1/4e", 1); REQUIRE(scenario.start_up()); auto &eu07{scenario.cab()}; - REQUIRE(eu07.lowVoltage.batteryVoltage == doctest::Approx(eu07.lowVoltage.nominalBatteryVoltage)); + REQUIRE(eu07.lowVoltage.BatteryVoltage() == doctest::Approx(eu07.lowVoltage.config.nominalBatteryVoltage)); scenario.act("converter off, lights on, small compressor on"); eu07.ConverterSwitch(false); eu07.iLights[VehicleEnd::front] = 1 | 2 | 4; eu07.iLights[VehicleEnd::rear] = 16; - eu07.pantographAir.compressorRunning = true; + eu07.pantographAir.SwitchCompressor(true); scenario.wait(30.0); - CHECK(eu07.lowVoltage.batteryVoltage < 0.83 * eu07.lowVoltage.nominalBatteryVoltage); + CHECK(eu07.lowVoltage.BatteryVoltage() < 0.83 * eu07.lowVoltage.config.nominalBatteryVoltage); CHECK(eu07.lineBreaker.IsClosed()); scenario.wait(5000.0); - CHECK(eu07.lowVoltage.batteryVoltage < eu07.lowVoltage.nominalBatteryVoltage / 1.57); + CHECK(eu07.lowVoltage.BatteryVoltage() < eu07.lowVoltage.config.nominalBatteryVoltage / 1.57); CHECK_FALSE(eu07.lineBreaker.IsClosed()); scenario.act("start up again"); CHECK_FALSE(scenario.start_up()); - CHECK(eu07.lowVoltage.batteryVoltage < eu07.lowVoltage.nominalBatteryVoltage / 1.57); + CHECK(eu07.lowVoltage.BatteryVoltage() < eu07.lowVoltage.config.nominalBatteryVoltage / 1.57); scenario.check(); } @@ -61,20 +61,20 @@ TEST_CASE("auxiliaries: the battery switched off, and charged by the converter") scenario.act("converter off"); eu07.ConverterSwitch(false); scenario.wait(10.0); - auto const discharged{eu07.lowVoltage.batteryVoltage}; - CHECK(discharged < 0.83 * eu07.lowVoltage.nominalBatteryVoltage); + auto const discharged{eu07.lowVoltage.BatteryVoltage()}; + CHECK(discharged < 0.83 * eu07.lowVoltage.config.nominalBatteryVoltage); // the converter charges it back at once scenario.act("converter on"); eu07.ConverterSwitch(true); scenario.wait(10.0); - CHECK(eu07.lowVoltage.batteryVoltage == doctest::Approx(eu07.lowVoltage.nominalBatteryVoltage)); + CHECK(eu07.lowVoltage.BatteryVoltage() == doctest::Approx(eu07.lowVoltage.config.nominalBatteryVoltage)); // switched off, the battery falls to 90 V at once, then holds scenario.act("battery off"); eu07.MainSwitch(false); eu07.ConverterSwitch(false); eu07.BatterySwitch(false); scenario.wait(10.0); - CHECK(eu07.lowVoltage.batteryVoltage == doctest::Approx(discharged).epsilon(0.01)); + CHECK(eu07.lowVoltage.BatteryVoltage() == doctest::Approx(discharged).epsilon(0.01)); scenario.check(); } @@ -90,23 +90,23 @@ TEST_CASE("auxiliaries: the pantographs on their own tank, leaking until the pre auto &eu07{scenario.cab()}; // started up on the small compressor, the tank gets joined to the main reservoir, which primes the switch scenario.act("tank joined to the main reservoir"); - eu07.pantographAir.connectedToMainReservoir = true; + eu07.pantographAir.ConnectToMainReservoir(true); scenario.wait(30.0); - REQUIRE(eu07.pantographAir.pressureSwitchActive); + REQUIRE(eu07.pantographAir.IsPressureSwitchPrimed()); scenario.act("tank cut off the main reservoir"); - eu07.pantographAir.connectedToMainReservoir = false; - eu07.pantographAir.compressorRunning = false; + eu07.pantographAir.ConnectToMainReservoir(false); + eu07.pantographAir.SwitchCompressor(false); scenario.wait(600.0); - CHECK(eu07.pantographAir.pressure < eu07.EnginePowerSource.CollectorParameters.MinPress); - CHECK_FALSE(eu07.pantographAir.pressureSwitchActive); + CHECK(eu07.pantographAir.Pressure() < eu07.EnginePowerSource.CollectorParameters.MinPress); + CHECK_FALSE(eu07.pantographAir.IsPressureSwitchPrimed()); CHECK_FALSE(eu07.lineBreaker.IsClosed()); scenario.act("small compressor on"); - eu07.pantographAir.compressorRunning = true; - for (int i = 0; i < 60 && eu07.pantographAir.compressorRunning; ++i) { + eu07.pantographAir.SwitchCompressor(true); + for (int i = 0; i < 60 && eu07.pantographAir.IsCompressorRunning(); ++i) { scenario.wait(10.0); } - CHECK_FALSE(eu07.pantographAir.compressorRunning); - CHECK(eu07.pantographAir.pressure >= 4.6); // stopped at 4.8, leaking since - CHECK(eu07.pantographAir.pressureSwitchActive); + CHECK_FALSE(eu07.pantographAir.IsCompressorRunning()); + CHECK(eu07.pantographAir.Pressure() >= 4.6); // stopped at 4.8, leaking since + CHECK(eu07.pantographAir.IsPressureSwitchPrimed()); scenario.check(); } diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index f4e2c4841..68f652b7f 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -47,14 +47,14 @@ std::vector state() { {"CompartmentLightsEnabled", [](auto const &M) { return flag(M.CompartmentLights.is_enabled); }}, {"CompartmentLightsDisabled", [](auto const &M) { return flag(M.CompartmentLights.is_disabled); }}, {"MainSwitch", [](auto const &M) { return flag(M.lineBreaker.IsClosed()); }}, - {"Heating", [](auto const &M) { return flag(M.trainHeating.on); }}, + {"Heating", [](auto const &M) { return flag(M.trainHeating.IsOn()); }}, {"DirActive", [](auto const &M) { return M.DirActive; }}, {"DirAbsolute", [](auto const &M) { return M.DirAbsolute; }}, {"CabActive", [](auto const &M) { return M.CabActive; }}, {"CabMaster", [](auto const &M) { return flag(M.CabMaster); }}, {"AutoRelayFlag", [](auto const &M) { return flag(M.AutoRelayFlag); }}, {"ConverterAllow", [](auto const &M) { return flag(M.converter.IsAllowed()); }}, - {"Battery", [](auto const &M) { return flag(M.lowVoltage.batteryOn); }}, + {"Battery", [](auto const &M) { return flag(M.lowVoltage.IsBatteryOn()); }}, {"CompressorAllow", [](auto const &M) { return flag(M.air.compressor.allow); }}, {"CompressorListPos", [](auto const &M) { return M.air.compressor.listPosition; }}, {"DoorLock", [](auto const &M) { return flag(M.Doors.lock_enabled); }}, @@ -410,7 +410,7 @@ TEST_CASE("commands: every switch of the cab, worked on a pair standing under th channels.insert(channels.end(), { {"PantFrontActive", [](auto const &M) { return flag(M.pantographs[VehicleEnd::front].is_active); }}, {"PantRearActive", [](auto const &M) { return flag(M.pantographs[VehicleEnd::rear].is_active); }}, - {"PantPress", [](auto const &M) { return M.pantographAir.pressure; }}, + {"PantPress", [](auto const &M) { return M.pantographAir.Pressure(); }}, {"GroundRelay", [](auto const &M) { return flag(M.protection.GroundHolds()); }}, {"ConverterFlag", [](auto const &M) { return flag(M.converter.IsRunning()); }}, {"CompressorFlag", [](auto const &M) { return flag(M.air.compressor.running); }}, diff --git a/tests/unit/test_compartment_lights.cpp b/tests/unit/test_compartment_lights.cpp index 917618544..8724a135b 100644 --- a/tests/unit/test_compartment_lights.cpp +++ b/tests/unit/test_compartment_lights.cpp @@ -20,32 +20,32 @@ void lights_check(vehicle &Car) { 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->lowVoltage.power24vAvailable = false; - car->lowVoltage.power110vAvailable = false; + car->lowVoltage.Set24vAvailableForTest(false); + car->lowVoltage.Set110vAvailableForTest(false); car->CompartmentLightsSwitch(true, range_t::local); // switch on, no power lights_check(car); CHECK_FALSE(car->CompartmentLights.is_active); - car->lowVoltage.power110vAvailable = true; // converter on + car->lowVoltage.Set110vAvailableForTest(true); // converter on lights_check(car); CHECK(car->CompartmentLights.is_active); CHECK(car->CompartmentLights.intensity == doctest::Approx(1.0)); - car->lowVoltage.power110vAvailable = false; // battery only: the lights stay on, dimmed - car->lowVoltage.power24vAvailable = true; + car->lowVoltage.Set110vAvailableForTest(false); // battery only: the lights stay on, dimmed + car->lowVoltage.Set24vAvailableForTest(true); lights_check(car); CHECK(car->CompartmentLights.is_active); CHECK(car->CompartmentLights.intensity == doctest::Approx(0.5)); - car->lowVoltage.power24vAvailable = false; // no power at all + car->lowVoltage.Set24vAvailableForTest(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->lowVoltage.power110vAvailable = true; + car->lowVoltage.Set110vAvailableForTest(true); lights_check(car); CHECK_FALSE(car->CompartmentLights.is_active); // manual start: off until switched on @@ -68,13 +68,13 @@ TEST_CASE("compartment lights: the off switch turns the lights off, the on switc 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->lowVoltage.power24vAvailable = false; - car->lowVoltage.power110vAvailable = false; + car->lowVoltage.Set24vAvailableForTest(false); + car->lowVoltage.Set110vAvailableForTest(false); lights_check(car); CHECK_FALSE(car->CompartmentLights.is_active); - car->lowVoltage.power110vAvailable = true; + car->lowVoltage.Set110vAvailableForTest(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 index 8bc096c5d..0433c1d1f 100644 --- a/tests/unit/test_compartment_lights_switch.cpp +++ b/tests/unit/test_compartment_lights_switch.cpp @@ -117,7 +117,7 @@ void toggle(vehicle &Car, cab_controls const &Cab) { // 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->lowVoltage.power110vAvailable = true; + Car->lowVoltage.Set110vAvailableForTest(true); lights_check(Car); REQUIRE_FALSE(Car->CompartmentLights.is_active); } diff --git a/tests/unit/test_compressor.cpp b/tests/unit/test_compressor.cpp index b9c8bc6fc..b4bc1a201 100644 --- a/tests/unit/test_compressor.cpp +++ b/tests/unit/test_compressor.cpp @@ -89,7 +89,7 @@ TEST_CASE("compressor: a compressor fed from the low voltage waits from the low run_compressor(vehicle, 10.0); REQUIRE_FALSE(vehicle->air.compressor.running); - vehicle->lowVoltage.power110vAvailable = true; + vehicle->lowVoltage.Set110vAvailableForTest(true); run_compressor(vehicle, 4.9); CHECK_FALSE(vehicle->air.compressor.running); run_compressor(vehicle, 0.2); @@ -178,15 +178,15 @@ TEST_CASE("compressor: fed from the converter it waits for the converter start d REQUIRE(loco->converter.config.startDelay == doctest::Approx(30.0)); loco.run(1.0); // engine off - CHECK_FALSE(loco->lowVoltage.power110vAvailable); + CHECK_FALSE(loco->lowVoltage.Is110vAvailable()); loco->lineBreaker.Close(); // engine started loco.run(25.0); - CHECK_FALSE(loco->lowVoltage.power110vAvailable); + CHECK_FALSE(loco->lowVoltage.Is110vAvailable()); CHECK_FALSE(loco->air.compressor.running); loco.run(10.0); - CHECK(loco->lowVoltage.power110vAvailable); + CHECK(loco->lowVoltage.Is110vAvailable()); CHECK(loco->air.compressor.running); } @@ -197,7 +197,7 @@ TEST_CASE("compressor: fed from the converter the start delay counts from the co loco.run(1.0); // engine off loco->lineBreaker.Close(); // engine started loco.run(25.0); - REQUIRE(loco->lowVoltage.power110vAvailable); // the converter is up + REQUIRE(loco->lowVoltage.Is110vAvailable()); // the converter is up CHECK_FALSE(loco->air.compressor.running); // but the compressor waits for its own delay as well loco.run(10.0); diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index a7f73561d..6d853f799 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -456,13 +456,13 @@ TEST_CASE("controls: train heating from the locomotive") { scenario.act("heating on"); cab.HeatingSwitch(true); scenario.wait(30.0); - CHECK(cab.trainHeating.on); - CHECK(scenario.vehicle(2).trainHeating.on); + CHECK(cab.trainHeating.IsOn()); + CHECK(scenario.vehicle(2).trainHeating.IsOn()); scenario.act("heating off"); cab.HeatingSwitch(false); scenario.wait(10.0); - CHECK_FALSE(cab.trainHeating.on); - CHECK_FALSE(scenario.vehicle(2).trainHeating.on); + CHECK_FALSE(cab.trainHeating.IsOn()); + CHECK_FALSE(scenario.vehicle(2).trainHeating.IsOn()); scenario.check(); } @@ -552,7 +552,7 @@ TEST_CASE("controls: the automatic electrodynamic brake of the EP09, in service scenario.add("bdhpumn_v3/bdhpumn", 0, test::consist::full_coupling, 120.0); REQUIRE(scenario.start_up()); auto &ep09{scenario.cab()}; - REQUIRE(ep09.lowVoltage.power110vAvailable); + REQUIRE(ep09.lowVoltage.Is110vAvailable()); scenario.act(std::string{"brake "} + name); ep09.BrakeLevelSet(ep09.brakes.driverValve->GetPos(bh_MB) + steps); scenario.wait(10.0); diff --git a/tests/unit/test_engine_shutdown.cpp b/tests/unit/test_engine_shutdown.cpp index b96aa011c..a841da08d 100644 --- a/tests/unit/test_engine_shutdown.cpp +++ b/tests/unit/test_engine_shutdown.cpp @@ -39,7 +39,7 @@ TEST_CASE("engine shutdown: neither the fuel pump switch nor the battery switch CHECK(shunter->lineBreaker.IsClosed()); shunter->BatterySwitch(false); shunter.run(10.0); - CHECK(shunter->lowVoltage.power110vAvailable); // the converter run by the engine keeps feeding the fuel pump + CHECK(shunter->lowVoltage.Is110vAvailable()); // the converter run by the engine keeps feeding the fuel pump CHECK(shunter->lineBreaker.IsClosed()); CHECK(shunter->enrot > 0.9 * shunter->diesel.minRevolutions); } diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index 1c32112ba..695f45193 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -133,8 +133,8 @@ TEST_CASE("genset: a vehicle without the keys has none and stays on the catenary CHECK(cab.TractionMode == traction_mode::catenary); CHECK_FALSE(cab.GensetSelected()); REQUIRE(test::start_up(test::driving(dragon6), wire)); - CHECK(cab.pantographCircuit.supplyVoltage > 2900.0); - CHECK(cab.TractionSupplyVoltage() == std::max(cab.GetTrainsetHighVoltage(), cab.pantographCircuit.supplyVoltage)); + CHECK(cab.pantographCircuit.SupplyVoltage() > 2900.0); + CHECK(cab.TractionSupplyVoltage() == std::max(cab.GetTrainsetHighVoltage(), cab.pantographCircuit.SupplyVoltage())); CHECK(cab.TractionSupplyMinVoltage() == cab.EnginePowerSource.CollectorParameters.MinV); CHECK(cab.GensetTractionPowerLimit() == std::numeric_limits::max()); // a start request does nothing without a genset @@ -230,7 +230,7 @@ TEST_CASE("genset: started, it closes the line breaker without a catenary") { run(dragon6, 1.0); } REQUIRE(cab.lineBreaker.IsClosed()); - CHECK(cab.pantographCircuit.supplyVoltage == 0.0); + CHECK(cab.pantographCircuit.SupplyVoltage() == 0.0); dragon6.step(no_wire); CHECK(cab.EngineVoltage == 3000.0); CHECK(cab.MainCircuitPowered()); @@ -263,7 +263,7 @@ TEST_CASE("genset: on the genset position the catenary feeds nothing") { 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.pantographCircuit.supplyVoltage > 2900.0); + REQUIRE(cab.pantographCircuit.SupplyVoltage() > 2900.0); CHECK_FALSE(cab.lineBreaker.IsClosed()); CHECK_FALSE(cab.MainSwitchCheck()); dragon6.step(wire); @@ -430,7 +430,7 @@ TEST_CASE("genset: no battery, no start") { REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); cab.GensetSwitch(true); run(dragon6, 20.0); - CHECK_FALSE(cab.lowVoltage.power24vAvailable); + CHECK_FALSE(cab.lowVoltage.Is24vAvailable()); CHECK_FALSE(cab.Genset.is_cranking); CHECK_FALSE(cab.Genset.is_active); CHECK(cab.Genset.revolutions == 0.0); @@ -445,8 +445,7 @@ TEST_CASE("genset: the pantographs' pressure switch leaves the genset's line bre vehicle dragon6{dragon_genset(), 0.0, "test", 1}; auto &cab{dragon6.physics()}; REQUIRE(start_on_genset(dragon6)); - cab.pantographAir.pressureSwitchActive = true; - cab.pantographAir.pressure = 0.0; + cab.pantographAir.SetForTest(0.0, true); cab.PantPressureSwitchCheck(); CHECK(cab.lineBreaker.IsClosed()); } @@ -456,8 +455,7 @@ TEST_CASE("genset: the pantographs' pressure switch leaves the genset's line bre REQUIRE(test::start_up(test::driving(dragon6), wire)); REQUIRE(cab.lineBreaker.IsClosed()); // the pressure switch looks at the voltage through the couplers, not the pantographs' - cab.pantographAir.pressureSwitchActive = true; - cab.pantographAir.pressure = 0.0; + cab.pantographAir.SetForTest(0.0, true); cab.PantPressureSwitchCheck(); CHECK_FALSE(cab.lineBreaker.IsClosed()); } @@ -536,7 +534,7 @@ TEST_CASE("genset: one genset feeds the next car through the high voltage coupli train.run(10.0, no_wire); REQUIRE(first.Genset.is_active); CHECK(second.GetTrainsetHighVoltage() > 2900.0); - CHECK(second.pantographCircuit.supplyVoltage == 0.0); + CHECK(second.pantographCircuit.SupplyVoltage() == 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); diff --git a/tests/unit/test_horn.cpp b/tests/unit/test_horn.cpp index e606f4105..021531986 100644 --- a/tests/unit/test_horn.cpp +++ b/tests/unit/test_horn.cpp @@ -79,9 +79,9 @@ TEST_CASE("horn: an electric horn sounds on the low voltage, whatever the air") REQUIRE(vehicle->Horn3Supply == horn_supply::electric); // the third horn follows the others unless told otherwise vehicle->air.mainReservoirPressure = 0.0; - vehicle->lowVoltage.power24vAvailable = true; + vehicle->lowVoltage.Set24vAvailableForTest(true); CHECK(vehicle->SoundingHorns(allhorns) == allhorns); - vehicle->lowVoltage.power24vAvailable = false; + vehicle->lowVoltage.Set24vAvailableForTest(false); CHECK(vehicle->SoundingHorns(allhorns) == 0); } @@ -91,10 +91,10 @@ TEST_CASE("horn: the third horn can have a supply of its own, an electric horn o REQUIRE(vehicle->Horn3Supply == horn_supply::electric); vehicle->air.mainReservoirPressure = 0.0; - vehicle->lowVoltage.power24vAvailable = true; + vehicle->lowVoltage.Set24vAvailableForTest(true); CHECK(vehicle->SoundingHorns(allhorns) == 4); vehicle->air.mainReservoirPressure = 6.5; - vehicle->lowVoltage.power24vAvailable = false; + vehicle->lowVoltage.Set24vAvailableForTest(false); CHECK(vehicle->SoundingHorns(allhorns) == (horn::low | horn::high)); } @@ -116,6 +116,6 @@ TEST_CASE("horn: a pneumatic horn sounds from the threshold pressure up") { TEST_CASE("horn: an electric horn sounds on 110 V too") { auto vehicle{horn_vehicle(test::definition::load("wagon").set("Cntrl", "HornType", "Electric"))}; - vehicle->lowVoltage.power110vAvailable = true; + vehicle->lowVoltage.Set110vAvailableForTest(true); CHECK(vehicle->SoundingHorns(horn::high) == horn::high); } diff --git a/tests/unit/test_line_contactors_interlock.cpp b/tests/unit/test_line_contactors_interlock.cpp index 94e658281..567834712 100644 --- a/tests/unit/test_line_contactors_interlock.cpp +++ b/tests/unit/test_line_contactors_interlock.cpp @@ -52,7 +52,7 @@ TEST_CASE("line contactors interlock: without one the converter and the blowers TEST_CASE("line contactors interlock: on the converter, they close only with the vehicle's own converter running") { auto locomotive{ready("Converter")}; locomotive->converter.SetRunningForTest(false); - locomotive->lowVoltage.power110vAvailable = true; // the 110 V from the other section doesn't run this one's fans + locomotive->lowVoltage.Set110vAvailableForTest(true); // the 110 V from the other section doesn't run this one's fans CHECK_FALSE(locomotive->MotorConnectorsCheck()); locomotive->converter.SetRunningForTest(true); CHECK(locomotive->MotorConnectorsCheck()); @@ -95,16 +95,16 @@ TEST_CASE("line contactors interlock: a blower starting with the speed needs to SUBCASE("off the converter, it needs the 110 V") { rear.start_type = start_t::converter; rear.is_enabled = false; // nothing for the driver to switch on - locomotive->lowVoltage.power110vAvailable = false; + locomotive->lowVoltage.Set110vAvailableForTest(false); CHECK_FALSE(locomotive->MotorConnectorsCheck()); - locomotive->lowVoltage.power110vAvailable = true; + locomotive->lowVoltage.Set110vAvailableForTest(true); CHECK(locomotive->MotorConnectorsCheck()); } SUBCASE("off the battery, it needs the 24 V") { rear.start_type = start_t::battery; - locomotive->lowVoltage.power24vAvailable = false; + locomotive->lowVoltage.Set24vAvailableForTest(false); CHECK_FALSE(locomotive->MotorConnectorsCheck()); - locomotive->lowVoltage.power24vAvailable = true; + locomotive->lowVoltage.Set24vAvailableForTest(true); CHECK(locomotive->MotorConnectorsCheck()); } SUBCASE("one without a start velocity still has to run") { @@ -271,7 +271,7 @@ TEST_CASE("line contactors interlock: the ET42 section with its fans switched of rear.converter.SetLocalSwitch(false); test::drive(driven, line, 2.0); REQUIRE_FALSE(rear.converter.IsRunning()); - CHECK(rear.lowVoltage.power110vAvailable); + CHECK(rear.lowVoltage.Is110vAvailable()); test::release_brakes(driven.cab); for (int i = 0; i < 3 && driven.cab.DirActive <= 0; ++i) { diff --git a/tests/unit/test_mains_before_pantographs.cpp b/tests/unit/test_mains_before_pantographs.cpp index fdbd4ca91..309556072 100644 --- a/tests/unit/test_mains_before_pantographs.cpp +++ b/tests/unit/test_mains_before_pantographs.cpp @@ -26,7 +26,7 @@ test::definition ep05(bool const Mainsfirst) { // battery and cab on, direction set and the relays reset, the pantographs on the main reservoir's air void prepare(test::vehicle &Loco) { Loco.hold_main_reservoir(6.0); - Loco->pantographAir.connectedToMainReservoir = true; + Loco->pantographAir.ConnectToMainReservoir(true); Loco->BatterySwitch(true); Loco->CabActivisation(); for (int i = 0; i < 3 && Loco->DirActive <= 0; ++i) { @@ -94,7 +94,7 @@ TEST_CASE("mains before pantographs: without the flag the line breaker needs the CHECK_FALSE(loco->lineBreaker.IsClosed()); raise_pantograph(loco); CHECK(loco->pantographs[VehicleEnd::rear].is_active); - CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); close_line_breaker(loco); CHECK(loco->lineBreaker.IsClosed()); // the pantographs stay up with the line breaker open, and the line breaker opens without voltage @@ -115,20 +115,20 @@ TEST_CASE("mains before pantographs: with the flag the pantographs rise only thr // the pantographs stay down while the line breaker is open raise_pantograph(loco); CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); - CHECK(loco->pantographCircuit.supplyVoltage == 0.0); + CHECK(loco->pantographCircuit.SupplyVoltage() == 0.0); // the line breaker closes without voltage, and the pantograph rises through it close_line_breaker(loco); CHECK(loco->lineBreaker.IsClosed()); raise_pantograph(loco); CHECK(loco->pantographs[VehicleEnd::rear].is_active); - CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); CHECK(loco->lineBreaker.IsClosed()); // opening the line breaker drops the pantograph, which stays down until the line breaker closes again loco->MainSwitch(false); loco.run(2.0, line); CHECK_FALSE(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); - CHECK(loco->pantographCircuit.supplyVoltage == 0.0); + CHECK(loco->pantographCircuit.SupplyVoltage() == 0.0); // a pantograph lowered under the closed line breaker leaves it closed close_line_breaker(loco); raise_pantograph(loco); @@ -153,7 +153,7 @@ TEST_CASE("mains before pantographs: with the flag the driver's start-up gets th auto driven{test::driving(loco)}; REQUIRE(test::start_up(driven, line)); CHECK(loco->lineBreaker.IsClosed()); - CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); CHECK(test::is_ready(driven)); } @@ -165,7 +165,7 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres prepare(loco); close_line_breaker(loco); REQUIRE(loco->lineBreaker.IsClosed()); - REQUIRE(loco->pantographCircuit.supplyVoltage == 0.0); + REQUIRE(loco->pantographCircuit.SupplyVoltage() == 0.0); switch_auxiliaries_on(loco); REQUIRE(loco->converter.IsAllowed()); REQUIRE(loco->air.compressor.allow); @@ -175,16 +175,16 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres CHECK(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->MainCircuitPowered()); CHECK_FALSE(loco->converter.IsRunning()); - CHECK_FALSE(loco->lowVoltage.power110vAvailable); + CHECK_FALSE(loco->lowVoltage.Is110vAvailable()); CHECK_FALSE(loco->air.compressor.running); // the pantograph up: the converter starts, and the compressor on its 110 V raise_pantograph(loco); - REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); + REQUIRE(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); CHECK(reservoir_gain(loco, 10.0, line) > 0.1); CHECK(loco->MainCircuitPowered()); CHECK(loco->converter.IsRunning()); - CHECK(loco->lowVoltage.power110vAvailable); + CHECK(loco->lowVoltage.Is110vAvailable()); CHECK(loco->air.compressor.running); // the voltage gone they stop, behind the line breaker which stays closed @@ -202,13 +202,13 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres SUBCASE("the voltage in the catenary below the one the locomotive works on") { track = &weak; loco.run(5.0, weak); - REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(weak.voltage)); + REQUIRE(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(weak.voltage)); } CHECK(reservoir_gain(loco, 10.0, *track) < 0.01); CHECK(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->MainCircuitPowered()); CHECK_FALSE(loco->converter.IsRunning()); - CHECK_FALSE(loco->lowVoltage.power110vAvailable); + CHECK_FALSE(loco->lowVoltage.Is110vAvailable()); CHECK_FALSE(loco->air.compressor.running); } @@ -231,26 +231,26 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui CHECK_FALSE(loco->air.compressor.running); CHECK_FALSE(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot == 0.0); - CHECK_FALSE(loco->trainHeating.on); + CHECK_FALSE(loco->trainHeating.IsOn()); SUBCASE("nor do they run on a voltage below the one the locomotive works on") { raise_pantograph(loco, weak); - REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(weak.voltage)); + REQUIRE(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(weak.voltage)); CHECK(reservoir_gain(loco, 10.0, weak) < 0.01); CHECK(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->air.compressor.running); CHECK_FALSE(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot == 0.0); - CHECK_FALSE(loco->trainHeating.on); + CHECK_FALSE(loco->trainHeating.IsOn()); } SUBCASE("with the voltage they do") { raise_pantograph(loco); - REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); + REQUIRE(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); CHECK(reservoir_gain(loco, 10.0, line) > 0.1); CHECK(loco->air.compressor.running); CHECK(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot > 0.0); - CHECK(loco->trainHeating.on); + CHECK(loco->trainHeating.IsOn()); } } @@ -264,14 +264,14 @@ TEST_CASE("mains before pantographs: without the flag the converter and the comp CHECK(reservoir_gain(loco, 10.0, line) > 0.1); CHECK(loco->MainCircuitPowered()); CHECK(loco->converter.IsRunning()); - CHECK(loco->lowVoltage.power110vAvailable); + CHECK(loco->lowVoltage.Is110vAvailable()); CHECK(loco->air.compressor.running); // too low a voltage opens the line breaker, and they stop with it loco.run(5.0, weak); CHECK_FALSE(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->MainCircuitPowered()); CHECK_FALSE(loco->converter.IsRunning()); - CHECK_FALSE(loco->lowVoltage.power110vAvailable); + CHECK_FALSE(loco->lowVoltage.Is110vAvailable()); CHECK_FALSE(loco->air.compressor.running); } @@ -296,7 +296,7 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when // the voltage back, with the master controller still where it was: the camshaft went down to zero and stays // there, the motors still cut off; the converter is back on its own test::drive(driven, line, 10.0); - REQUIRE(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); + REQUIRE(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); REQUIRE(loco->MainCtrlPos == 5); CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->converter.IsRunning()); diff --git a/tests/unit/test_oil_pump.cpp b/tests/unit/test_oil_pump.cpp index 94e590208..674930af2 100644 --- a/tests/unit/test_oil_pump.cpp +++ b/tests/unit/test_oil_pump.cpp @@ -12,7 +12,7 @@ using test::vehicle; TEST_CASE("oil pump: the pre-lubrication pump works before the engine start and stops once the engine runs") { vehicle loco{definition::load("cab_vehicle").set("Cntrl", "OilStart", "Manual")}; REQUIRE(loco->OilPump.start_type == start_t::manual); - loco->lowVoltage.power24vAvailable = true; // battery on + loco->lowVoltage.Set24vAvailableForTest(true); // battery on loco->OilPumpCheck(0.01); CHECK_FALSE(loco->OilPump.is_active); // not switched on yet @@ -29,7 +29,7 @@ TEST_CASE("oil pump: the pre-lubrication pump works before the engine start and TEST_CASE("oil pump: the pump started with the engine start procedure stops once the engine runs") { vehicle loco{definition::load("cab_vehicle").set("Cntrl", "OilStart", "Automatic")}; REQUIRE(loco->OilPump.start_type == start_t::automatic); - loco->lowVoltage.power24vAvailable = true; + loco->lowVoltage.Set24vAvailableForTest(true); loco->diesel.startupRequested = true; // starter button pressed loco->OilPumpCheck(0.01); @@ -46,8 +46,8 @@ TEST_CASE("oil pump: the pump started with the engine start procedure stops once TEST_CASE("oil pump: without power the pump and its lamp stay off") { vehicle loco{definition::load("cab_vehicle")}; - loco->lowVoltage.power24vAvailable = false; - loco->lowVoltage.power110vAvailable = false; + loco->lowVoltage.Set24vAvailableForTest(false); + loco->lowVoltage.Set110vAvailableForTest(false); loco->OilPump.is_enabled = true; loco->OilPumpCheck(0.01); diff --git a/tests/unit/test_pressure_switch.cpp b/tests/unit/test_pressure_switch.cpp index 2c30692d6..a45260b49 100644 --- a/tests/unit/test_pressure_switch.cpp +++ b/tests/unit/test_pressure_switch.cpp @@ -169,7 +169,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller CHECK_FALSE(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->pantographs[VehicleEnd::front].is_active); CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); - CHECK(loco->pantographCircuit.supplyVoltage == 0.0); + CHECK(loco->pantographCircuit.SupplyVoltage() == 0.0); CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->Im == 0.0); @@ -193,7 +193,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller emergency_application(loco, driven); CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); - CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographCircuit.SupplyVoltage() == 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 @@ -234,7 +234,7 @@ TEST_CASE("pressure switch: without the key an emergency application leaves the REQUIRE(loco->MainCtrlPos == 5); CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); - CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); // the pressure switch cuts the motors off CHECK(loco->protection.PressureSwitchTripped()); CHECK_FALSE(loco->lineContactors.IsClosed()); @@ -250,7 +250,7 @@ TEST_CASE("pressure switch: where the pantographs don't hang on the line breaker emergency_application(loco, driven); CHECK_FALSE(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); - CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->Im == 0.0); } @@ -272,7 +272,7 @@ TEST_CASE("pressure switch: after the emergency application the driver's start-u CHECK(loco->MainCtrlPos == 0); CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); - CHECK(loco->pantographCircuit.supplyVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); REQUIRE(loco->brakePipe.pressure < emergency_pressure); // and it stays so test::drive(driven, line, 30.0); diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp index 62f620270..d75fb2611 100644 --- a/tests/unit/test_pullee.cpp +++ b/tests/unit/test_pullee.cpp @@ -114,13 +114,13 @@ TEST_CASE("pullee: an EU07 with a driver can't release the brakes of a dead Vect 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->lowVoltage.batteryOn); + CHECK(hauled->lowVoltage.IsBatteryOn()); CHECK(locomotive->brakePipe.pressure < 1.0); CHECK(locomotive->brakes.cylinderPressure > 3.0); CHECK(hauled->brakes.cylinderPressure > 3.0); continue; } - CHECK_FALSE(hauled->lowVoltage.batteryOn); + CHECK_FALSE(hauled->lowVoltage.IsBatteryOn()); CHECK(locomotive->brakePipe.pressure > 4.9); CHECK(locomotive->brakes.cylinderPressure < 0.1); CHECK(hauled->brakes.cylinderPressure < 0.1); @@ -335,9 +335,9 @@ TEST_CASE("pullee: entering the mode lets go of the hand brake and the spring br } SUBCASE("a locomotive ready to depart, its battery on") { vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.1}; - REQUIRE(vectron->lowVoltage.batteryOn); + REQUIRE(vectron->lowVoltage.IsBatteryOn()); CHECK(vectron->PulleeModeSwitch(true)); - CHECK_FALSE(vectron->lowVoltage.batteryOn); + CHECK_FALSE(vectron->lowVoltage.IsBatteryOn()); } } @@ -345,7 +345,7 @@ TEST_CASE("pullee: the battery and the cabs of a vehicle prepared for hauling st vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.0, "test", 1}; REQUIRE(vectron->PulleeModeSwitch(true)); CHECK_FALSE(vectron->BatterySwitch(true)); - CHECK_FALSE(vectron->lowVoltage.batteryOn); + CHECK_FALSE(vectron->lowVoltage.IsBatteryOn()); CHECK_FALSE(vectron->CabActivisation()); CHECK_FALSE(vectron->CabActivisation(true)); CHECK(vectron->CabActive == 0); @@ -357,7 +357,7 @@ TEST_CASE("pullee: the battery and the cabs of a vehicle prepared for hauling st REQUIRE(vectron->PulleeModeSwitch(false)); CHECK_FALSE(vectron->PulleeMode); CHECK(vectron->BatterySwitch(true)); - CHECK(vectron->lowVoltage.batteryOn); + CHECK(vectron->lowVoltage.IsBatteryOn()); CHECK(vectron->CabActivisation()); CHECK(vectron->CabActive == 1); // a vehicle driven from isn't one to haul @@ -394,14 +394,14 @@ TEST_CASE("pullee: the battery and cab commands of the train's driver pass a veh if (pullee) { REQUIRE(hauled->PulleeModeSwitch(true)); } - REQUIRE_FALSE(hauled->lowVoltage.batteryOn); + REQUIRE_FALSE(hauled->lowVoltage.IsBatteryOn()); locomotive->BatterySwitch(true); locomotive->CabActivisation(); train.run(2.0); - CHECK(hauled->lowVoltage.batteryOn == (false == pullee)); + CHECK(hauled->lowVoltage.IsBatteryOn() == (false == pullee)); CHECK(hauled->CabActive == (pullee ? 0 : 1)); // the vehicle behind it gets them either way - CHECK(last->lowVoltage.batteryOn); + CHECK(last->lowVoltage.IsBatteryOn()); CHECK(last->CabActive == 1); } } @@ -439,7 +439,7 @@ TEST_CASE("pullee: every real vehicle standing braked releases once prepared for auto const &hauled{train.hauled.physics()}; CHECK(hauled.brakes.handBrakePosition == 0); CHECK_FALSE(hauled.brakes.spring.activate); - CHECK_FALSE(hauled.lowVoltage.batteryOn); + CHECK_FALSE(hauled.lowVoltage.IsBatteryOn()); train.run(180.0); CHECK(hauled.brakes.emergencyValve.flow == 0.0); CHECK(hauled.brakes.cylinderPressure < 0.1); diff --git a/tests/unit/test_radio.cpp b/tests/unit/test_radio.cpp index abe4ef9f8..696624cce 100644 --- a/tests/unit/test_radio.cpp +++ b/tests/unit/test_radio.cpp @@ -8,8 +8,8 @@ TEST_CASE("radio: a radio switched on with the low voltage works") { test::vehicle vehicle{test::definition::load("wagon")}; vehicle->Radio = true; - SUBCASE("24 V") { vehicle->lowVoltage.power24vAvailable = true; } - SUBCASE("110 V") { vehicle->lowVoltage.power110vAvailable = true; } + SUBCASE("24 V") { vehicle->lowVoltage.Set24vAvailableForTest(true); } + SUBCASE("110 V") { vehicle->lowVoltage.Set110vAvailableForTest(true); } CHECK(vehicle->RadioPowered()); } @@ -17,12 +17,12 @@ TEST_CASE("radio: a radio switched off or without the low voltage doesn't") { test::vehicle vehicle{test::definition::load("wagon")}; SUBCASE("switched off") { vehicle->Radio = false; - vehicle->lowVoltage.power24vAvailable = true; + vehicle->lowVoltage.Set24vAvailableForTest(true); } SUBCASE("batteries off") { vehicle->Radio = true; - vehicle->lowVoltage.power24vAvailable = false; - vehicle->lowVoltage.power110vAvailable = false; + vehicle->lowVoltage.Set24vAvailableForTest(false); + vehicle->lowVoltage.Set110vAvailableForTest(false); } CHECK_FALSE(vehicle->RadioPowered()); } @@ -38,7 +38,7 @@ TEST_CASE("radio: the radio fuse is closed by default") { TEST_CASE("radio: an opened radio fuse cuts the radio off") { test::vehicle vehicle{test::definition::load("wagon")}; vehicle->Radio = true; - vehicle->lowVoltage.power24vAvailable = true; + vehicle->lowVoltage.Set24vAvailableForTest(true); vehicle->RadioFuse = false; CHECK_FALSE(vehicle->RadioPowered()); vehicle->RadioFuse = true; @@ -47,7 +47,7 @@ TEST_CASE("radio: an opened radio fuse cuts the radio off") { TEST_CASE("radio: opening the radio fuse at a standstill resets the radio-stop, as switching the radio off does") { test::vehicle loco{test::definition::fiz("4e_v1/4e")}; - loco->lowVoltage.batteryOn = true; + loco->lowVoltage.SetBatteryOnForTest(true); loco->Radio = true; REQUIRE(loco->RadiostopSwitch(true)); loco->SecuritySystemCheck(0.1); diff --git a/tests/unit/test_switches.cpp b/tests/unit/test_switches.cpp index f2ca6de17..444606524 100644 --- a/tests/unit/test_switches.cpp +++ b/tests/unit/test_switches.cpp @@ -7,10 +7,10 @@ TEST_CASE("switches: the train heating switch can spring back (MaSzyna-EU07/maszyna#85)") { SUBCASE("impulse") { test::vehicle vehicle{test::definition::load("cab_vehicle").set("Switches", "TrainHeating", "Impulse")}; - CHECK(vehicle->trainHeating.switchImpulse); // whichever the case it's written in + CHECK(vehicle->trainHeating.config.switchImpulse); // whichever the case it's written in } SUBCASE("a plain switch by default") { test::vehicle vehicle{test::definition::load("cab_vehicle")}; - CHECK_FALSE(vehicle->trainHeating.switchImpulse); + CHECK_FALSE(vehicle->trainHeating.config.switchImpulse); } } diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index 4e98ed74f..88e7a3b99 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -225,15 +225,15 @@ double vehicle::move(track const &Track, double Dt, TLocation const &Location, d // what TDynamicObject::Update() does before the movement. a raised pantograph touches the wire at once, // the game animates its rise auto &physics{*m_physics}; - physics.pantographCircuit.frontVoltage = physics.pantographs[VehicleEnd::front].is_active ? Track.voltage : 0.0; - physics.pantographCircuit.rearVoltage = physics.pantographs[VehicleEnd::rear].is_active ? Track.voltage : 0.0; + physics.pantographCircuit.SetFrontVoltage(physics.pantographs[VehicleEnd::front].is_active ? Track.voltage : 0.0); + physics.pantographCircuit.SetRearVoltage(physics.pantographs[VehicleEnd::rear].is_active ? Track.voltage : 0.0); TTractionParam traction; traction.TractionVoltage = - physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? std::max(std::abs(physics.pantographCircuit.rearVoltage), std::abs(physics.pantographCircuit.frontVoltage)) : 0.95 * physics.EnginePowerSource.MaxVoltage; + physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? std::max(std::abs(physics.pantographCircuit.RearVoltage()), std::abs(physics.pantographCircuit.FrontVoltage())) : 0.95 * physics.EnginePowerSource.MaxVoltage; traction.TractionFreq = 0; traction.TractionMaxCurrent = 7500; traction.TractionResistivity = 0.3; - physics.pantographCircuit.supplyVoltage = traction.TractionVoltage; + physics.pantographCircuit.SetSupplyVoltage(traction.TractionVoltage); if (m_cab != 0) { using enum TEngineType; // the driver's own vehicle, which gets the average pressure of the train's brake pipe diff --git a/vehicle/Gauge.cpp b/vehicle/Gauge.cpp index 0944fe83b..48b21ac1c 100644 --- a/vehicle/Gauge.cpp +++ b/vehicle/Gauge.cpp @@ -509,25 +509,25 @@ TGauge TGauge::MirrorCopy() const { return mirror; } -void TGauge::AssignFloat(float *fValue) +void TGauge::AssignFloat(float const *fValue) { m_datatype = 'f'; fData = fValue; }; -void TGauge::AssignDouble(double *dValue) +void TGauge::AssignDouble(double const *dValue) { m_datatype = 'd'; dData = dValue; }; -void TGauge::AssignInt(int *iValue) +void TGauge::AssignInt(int const *iValue) { m_datatype = 'i'; iData = iValue; }; -void TGauge::AssignBool(bool *bValue) +void TGauge::AssignBool(bool const *bValue) { m_datatype = 'b'; bData = bValue; diff --git a/vehicle/Gauge.h b/vehicle/Gauge.h index 9c93057c1..0bda4f2b6 100644 --- a/vehicle/Gauge.h +++ b/vehicle/Gauge.h @@ -55,10 +55,10 @@ public: float GetValue() const; float GetDesiredValue() const; void Update( bool const Power = true ); - void AssignFloat(float *fValue); - void AssignDouble(double *dValue); - void AssignInt(int *iValue); - void AssignBool(bool *bValue); + void AssignFloat(float const *fValue); + void AssignDouble(double const *dValue); + void AssignInt(int const *iValue); + void AssignBool(bool const *bValue); void UpdateValue(); void AssignState( bool const *State ); // copies of the control animated along with it, from its definitions marked duplicate: yes @@ -142,10 +142,10 @@ private: char m_datatype { '\0' }; // typ zmiennej parametru: f-float, d-double, i-int, b-bool; none until one is assigned union { // wskaźnik na parametr pokazywany przez animację - float *fData; - double *dData { nullptr }; - int *iData; - bool *bData; + float const *fData; + double const *dData { nullptr }; + int const *iData; + bool const *bData; }; bool m_state { false }; // visibility of the control's submodel(s); false : default, true: active bool const *m_stateinput { nullptr }; // bound variable determining visibility of the control's submodel(s) diff --git a/vehicle/Train.h b/vehicle/Train.h index 078a06064..89892b423 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -970,6 +970,7 @@ private: float fMainRelayTimer; // hunter-141211: zalaczanie WSa z opoznieniem float fBatteryTimer = {-1.f}; // Hirek: zalaczanie baterii z opoznieniem (tylko gdy zdefiniowano takie zachowanie w fiz) bool allowBatteryToggle = true; // Hirek: zabezpieczenie przed przelaczaniem bateri on/off + bool batteryButtonFired{false}; // the battery button held down has switched the battery already, until it is let go int ScreenUpdateRate { 0 }; // vehicle specific python screen update rate override // McZapkie-240302 - przyda sie do tachometru diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index 2ced8b5f1..ca3fb0934 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -379,8 +379,8 @@ bool TController::CheckVehicles(DriverOrders user) // HACK: wagony muszą mieć baterię załączoną do otwarcia drzwi... p->physics->BatterySwitch( true ); // enable heating and converter in carriages with can be heated - if( p->physics->trainHeating.power > 0 ) { - p->physics->trainHeating.allow = true; + if( p->physics->trainHeating.config.power > 0 ) { + p->physics->trainHeating.Allow(true); p->physics->ConverterSwitch( true, range_t::local ); hasheaters = true; } @@ -485,7 +485,7 @@ bool TController::CheckVehicles(DriverOrders user) false == isheatingcouplingactive ? false : ispassengertrain ? hasheaters : false) }; - if( mvControlling->trainHeating.allow != isheatingneeded ) { + if( mvControlling->trainHeating.IsAllowed() != isheatingneeded ) { cue_action( isheatingneeded ? driver_hint::consistheatingon : @@ -680,12 +680,12 @@ TController::determine_consist_state() { // ABu-160305 testowanie gotowości do jazdy // Ra: przeniesione z DynObj, skład użytkownika też jest testowany, żeby mu przekazać, że ma odhamować - if (occupied->CabActive == 0 && occupied->lowVoltage.power24vAvailable) + if (occupied->CabActive == 0 && occupied->lowVoltage.Is24vAvailable()) { cue_action( driver_hint::cabactivation ); } else if (!occupied->AutomaticCabActivation - && ( occupied->CabActive == -occupied->CabOccupied || !occupied->CabMaster || !occupied->lowVoltage.power24vAvailable ) ) + && ( occupied->CabActive == -occupied->CabOccupied || !occupied->CabMaster || !occupied->lowVoltage.Is24vAvailable() ) ) { cue_action( driver_hint::cabdeactivation ); } diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index 58b77d265..0b9bc5cb6 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -506,7 +506,7 @@ bool TController::IncSpeed() } // TODO: move all fVoltage assignments to a single, more generic place if( mvControlling->EnginePowerSource.SourceType == TPowerSource::Accumulator ) { - fVoltage = mvControlling->lowVoltage.batteryVoltage; + fVoltage = mvControlling->lowVoltage.BatteryVoltage(); } if (!IsAnyMotorOverloadRelayOpen && !mvControlling->protection.PressureSwitchTripped() && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->lineContactors.IsClosed()) && (Ready || drivingFlags.press)) { // youBy polecił dodać 2012-09-08 v367 diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index b70f23289..e665c6248 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -102,21 +102,21 @@ bool TController::PrepareEngine() if( pantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { // if our pantograph unit isn't a pantograph-devoid fallback - if (pantographUnit->pantographAir.pressure < sufficientpantographpressure) { + if (pantographUnit->pantographAir.Pressure() < sufficientpantographpressure) { // załączenie małej sprężarki - if( false == pantographUnit->pantographAir.autoValve ) { + if( false == pantographUnit->pantographAir.config.autoValve ) { // odłączenie zbiornika głównego, bo z nim nie da rady napompować cue_action( driver_hint::pantographairsourcesetauxiliary ); } cue_action( driver_hint::pantographcompressoron ); // załączenie sprężarki pantografów - if( pantographUnit->pantographAir.compressorRunning ) { + if( pantographUnit->pantographAir.IsCompressorRunning() ) { cue_action( driver_hint::waitpantographpressuretoolow ); } } else { // jeżeli jest wystarczające ciśnienie w pantografach - if( false == pantographUnit->pantographAir.connectedToMainReservoir - || pantographUnit->pantographAir.pressure <= pantographUnit->mainPipe.pressure ) { // kurek przełączony albo główna już pompuje + if( false == pantographUnit->pantographAir.IsConnectedToMainReservoir() + || pantographUnit->pantographAir.Pressure() <= pantographUnit->mainPipe.pressure ) { // kurek przełączony albo główna już pompuje cue_action( driver_hint::pantographcompressoroff ); // sprężarkę pantografów można już wyłączyć } } @@ -130,7 +130,7 @@ bool TController::PrepareEngine() auto const ispoweravailable = mvControlling->EnginePowerSource.SourceType != TPowerSource::CurrentCollector - || std::max(mvControlling->GetTrainsetHighVoltage(), mvControlling->pantographCircuit.supplyVoltage) > mvControlling->EnginePowerSource.CollectorParameters.MinV; + || std::max(mvControlling->GetTrainsetHighVoltage(), mvControlling->pantographCircuit.SupplyVoltage()) > 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 ); @@ -235,7 +235,7 @@ TController::report_power_stall( bool const Poweravailable, double const Pantogr state.collector = mvControlling->EnginePowerSource.SourceType == TPowerSource::CurrentCollector; state.power = Poweravailable; state.standing = occupied->Vel < EU07_AI_NOMOVEMENT; - if( pantographUnit->pantographAir.pressure >= Pantographpressure ) { + if( pantographUnit->pantographAir.Pressure() >= Pantographpressure ) { state.pantographs_up = pantographUnit->pantographs[ VehicleEnd::front ].is_active || pantographUnit->pantographs[ VehicleEnd::rear ].is_active; @@ -339,7 +339,7 @@ bool TController::ReleaseEngine() { // && ( false == IsAnyCompressorEnabled ) // && ( false == IsAnyConverterEnabled ) && false == mvControlling->lineBreaker.IsClosed() - && false == occupied->lowVoltage.power24vAvailable }; + && false == occupied->lowVoltage.Is24vAvailable() }; if (OK) { // jeśli się zatrzymał diff --git a/vehicle/ai/orders.cpp b/vehicle/ai/orders.cpp index 954c56dfc..0c1acba8f 100644 --- a/vehicle/ai/orders.cpp +++ b/vehicle/ai/orders.cpp @@ -1178,7 +1178,7 @@ TController::handle_engine() { if( OrderCurrentGet() == DriverOrder::waitForOrders && false == iEngineActive // && ( false == AIControllFlag ) - && true == occupied->lowVoltage.power24vAvailable ) { + && true == occupied->lowVoltage.Is24vAvailable() ) { OrderNext( DriverOrder::prepareEngine ); } // basic engine preparation diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index af896e558..755e24f7a 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -142,14 +142,14 @@ TController::control_pantographs() { if( pantographUnit->EnginePowerSource.SourceType != TPowerSource::CurrentCollector ) { return; } - if( false == pantographUnit->pantographAir.autoValve + if( false == pantographUnit->pantographAir.config.autoValve && occupied->mainPipe.pressure > 4.3 ) { // gdy główna sprężarka bezpiecznie nabije ciśnienie to można przestawić kurek na zasilanie pantografów z głównej pneumatyki cue_action( driver_hint::pantographairsourcesetmain ); } // uśrednione napięcie sieci: przy spadku poniżej wartości minimalnej opóźnić rozruch o losowy czas - fVoltage = 0.5 * (fVoltage + std::max( mvControlling->GetTrainsetHighVoltage(), mvControlling->pantographCircuit.supplyVoltage ) ); + fVoltage = 0.5 * (fVoltage + std::max( mvControlling->GetTrainsetHighVoltage(), mvControlling->pantographCircuit.SupplyVoltage() ) ); if( fVoltage < mvControlling->EnginePowerSource.CollectorParameters.MinV && fActionTime >= PrepareTime ) { // gdy rozłączenie WS z powodu niskiego napięcia // jeśli czas oczekiwania nie został ustawiony, losowy czas oczekiwania przed ponownym załączeniem jazdy @@ -197,18 +197,18 @@ TController::control_pantographs() { // jazda na tylnym if( iDirection >= 0 && useregularpantographlayout ) { // jak jedzie w kierunku sprzęgu 0 - if( pantographUnit->pantographCircuit.rearVoltage == 0.0 + if( pantographUnit->pantographCircuit.RearVoltage() == 0.0 // filter out cases with single _other_ working pantograph so we don't try to raise something we can't - && ( pantographUnit->pantographCircuit.supplyVoltage == 0.0 + && ( pantographUnit->pantographCircuit.SupplyVoltage() == 0.0 || pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { cue_action( driver_hint::rearpantographvalveon ); } } else { // jak jedzie w kierunku sprzęgu 0 - if( pantographUnit->pantographCircuit.frontVoltage == 0.0 + if( pantographUnit->pantographCircuit.FrontVoltage() == 0.0 // filter out cases with single _other_ working pantograph so we don't try to raise something we can't - && ( pantographUnit->pantographCircuit.supplyVoltage == 0.0 + && ( pantographUnit->pantographCircuit.SupplyVoltage() == 0.0 || pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { cue_action( driver_hint::frontpantographvalveon ); } @@ -218,14 +218,14 @@ TController::control_pantographs() { // opuszczenie przedniego po rozpędzeniu się o ile jest więcej niż jeden if (iDirection >= 0 && useregularpantographlayout) // jak jedzie w kierunku sprzęgu 0 { // poczekać na podniesienie tylnego - if (pantographUnit->pantographCircuit.frontVoltage != 0.0 && pantographUnit->pantographCircuit.rearVoltage != 0.0) + if (pantographUnit->pantographCircuit.FrontVoltage() != 0.0 && pantographUnit->pantographCircuit.RearVoltage() != 0.0) { // czy jest napięcie zasilające na tylnym? cue_action(driver_hint::frontpantographvalveoff); // opuszcza od sprzęgu 0 } } else { // poczekać na podniesienie przedniego - if (pantographUnit->pantographCircuit.rearVoltage != 0.0 && pantographUnit->pantographCircuit.frontVoltage != 0.0) + if (pantographUnit->pantographCircuit.RearVoltage() != 0.0 && pantographUnit->pantographCircuit.FrontVoltage() != 0.0) { // czy jest napięcie zasilające na przednim? cue_action(driver_hint::rearpantographvalveoff); // opuszcza od sprzęgu 1 } @@ -262,14 +262,14 @@ TController::control_pantographs() { if (iDirection >= 0 && useregularpantographlayout) { // jak jedzie w kierunku sprzęgu 0 - if (pantographUnit->pantographCircuit.frontVoltage == 0.0) + if (pantographUnit->pantographCircuit.FrontVoltage() == 0.0) { cue_action(driver_hint::frontpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h } } else { - if (pantographUnit->pantographCircuit.rearVoltage == 0.0) + if (pantographUnit->pantographCircuit.RearVoltage() == 0.0) { cue_action(driver_hint::rearpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h } @@ -291,7 +291,7 @@ TController::control_pantographs_setup( int const Setup ) { if( rear ) { cue_action( driver_hint::rearpantographvalveon ); } - if( auto const setuplive { ( front && pantographUnit->pantographCircuit.frontVoltage != 0.0 ) || ( rear && pantographUnit->pantographCircuit.rearVoltage != 0.0 ) }; + if( auto const setuplive { ( front && pantographUnit->pantographCircuit.FrontVoltage() != 0.0 ) || ( rear && pantographUnit->pantographCircuit.RearVoltage() != 0.0 ) }; false == setuplive ) { return; } diff --git a/vehicle/cab/auxiliarycommands.cpp b/vehicle/cab/auxiliarycommands.cpp index b2c8b50d3..268e974b2 100644 --- a/vehicle/cab/auxiliarycommands.cpp +++ b/vehicle/cab/auxiliarycommands.cpp @@ -684,7 +684,7 @@ void TTrain::OnCommand_convertertoggle(TTrain *Train, command_data const &Comman // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const overloadrelayisopen{(Train->Dynamic()->Mechanik != nullptr ? Train->Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : Train->occupied->converter.IsOverloaded())}; - if (Train->occupied->converter.config.switchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->occupied->lowVoltage.power110vAvailable && false == overloadrelayisopen) + if (Train->occupied->converter.config.switchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->occupied->lowVoltage.Is110vAvailable() && false == overloadrelayisopen) { // turn on OnCommand_converterenable(Train, Command); diff --git a/vehicle/cab/cabcommands.cpp b/vehicle/cab/cabcommands.cpp index 30f020482..8db842f8c 100644 --- a/vehicle/cab/cabcommands.cpp +++ b/vehicle/cab/cabcommands.cpp @@ -300,7 +300,7 @@ void TTrain::OnCommand_batterytoggle(TTrain *Train, command_data const &Command) if (Train->allowBatteryToggle || Command.action != GLFW_REPEAT) { // keep the switch from flipping back and forth if key is held down - if (false == Train->occupied->lowVoltage.power24vAvailable) + if (false == Train->occupied->lowVoltage.Is24vAvailable()) { // turn on OnCommand_batteryenable(Train, Command); @@ -315,7 +315,7 @@ void TTrain::OnCommand_batterytoggle(TTrain *Train, command_data const &Command) void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) { - if (!Train->occupied->lowVoltage.batteryButtonImpulse) + if (!Train->occupied->lowVoltage.config.batteryButtonImpulse) { // regular button behavior if (Command.action == GLFW_PRESS) { @@ -346,12 +346,12 @@ void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) { if (Command.action == GLFW_PRESS) { - if (Train->occupied->lowVoltage.batteryButtonHeld) + if (Train->occupied->lowVoltage.config.batteryButtonHeld) { // jesli przycisk trzeba przytrzymac Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->fBatteryTimer = Train->occupied->lowVoltage.batteryButtonHoldTime; // start timer + Train->fBatteryTimer = Train->occupied->lowVoltage.config.batteryButtonHoldTime; // start timer } else { @@ -376,15 +376,15 @@ void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) Train->ggBatteryOnButton.UpdateValue(0.0f, Train->dsbSwitch); Train->fBatteryTimer = -1.f; // Train->allowBatteryToggle = true; - Train->occupied->lowVoltage.batteryButtonFired = false; + Train->batteryButtonFired = false; } - else if (Command.action == GLFW_REPEAT && Train->occupied->lowVoltage.batteryButtonHeld) + else if (Command.action == GLFW_REPEAT && Train->occupied->lowVoltage.config.batteryButtonHeld) { // trzymamy przycisk - if (Train->fBatteryTimer <= 0.0 && Train->occupied->lowVoltage.batteryOn == false && !Train->occupied->lowVoltage.batteryButtonFired) + if (Train->fBatteryTimer <= 0.0 && Train->occupied->lowVoltage.IsBatteryOn() == false && !Train->batteryButtonFired) { Train->occupied->BatterySwitch(true); - Train->occupied->lowVoltage.batteryButtonFired = true; + Train->batteryButtonFired = true; // side-effects if (Train->occupied->LightsPosNo > 0) @@ -399,7 +399,7 @@ void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) void TTrain::OnCommand_batterydisable(TTrain *Train, command_data const &Command) { - if (!Train->occupied->lowVoltage.batteryButtonImpulse) + if (!Train->occupied->lowVoltage.config.batteryButtonImpulse) { // regular button behavior if (Command.action == GLFW_PRESS) { @@ -429,12 +429,12 @@ void TTrain::OnCommand_batterydisable(TTrain *Train, command_data const &Command { if (Command.action == GLFW_PRESS) { - if (Train->occupied->lowVoltage.batteryButtonHeld) + if (Train->occupied->lowVoltage.config.batteryButtonHeld) { // jesli przycisk trzeba przytrzymac Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->fBatteryTimer = Train->occupied->lowVoltage.batteryButtonHoldTime; // start timer + Train->fBatteryTimer = Train->occupied->lowVoltage.config.batteryButtonHoldTime; // start timer } else { @@ -458,15 +458,15 @@ void TTrain::OnCommand_batterydisable(TTrain *Train, command_data const &Command Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); Train->ggBatteryOffButton.UpdateValue(0.0f, Train->dsbSwitch); Train->allowBatteryToggle = true; - Train->occupied->lowVoltage.batteryButtonFired = false; + Train->batteryButtonFired = false; } - else if (Command.action == GLFW_REPEAT && Train->occupied->lowVoltage.batteryButtonHeld) + else if (Command.action == GLFW_REPEAT && Train->occupied->lowVoltage.config.batteryButtonHeld) { // trzymamy przycisk - if (Train->fBatteryTimer <= 0.0 && Train->occupied->lowVoltage.batteryOn == true && !Train->occupied->lowVoltage.batteryButtonFired) + if (Train->fBatteryTimer <= 0.0 && Train->occupied->lowVoltage.IsBatteryOn() == true && !Train->batteryButtonFired) { Train->occupied->BatterySwitch(false); - Train->occupied->lowVoltage.batteryButtonFired = true; + Train->batteryButtonFired = true; // side-effects if (Train->occupied->LightsPosNo > 0) diff --git a/vehicle/cab/equipmentcommands.cpp b/vehicle/cab/equipmentcommands.cpp index 398836221..c1d974872 100644 --- a/vehicle/cab/equipmentcommands.cpp +++ b/vehicle/cab/equipmentcommands.cpp @@ -62,7 +62,7 @@ void TTrain::OnCommand_heatingtoggle(TTrain *Train, command_data const &Command) if (Command.action == GLFW_PRESS) { // ignore repeats so the switch doesn't flip back and forth if key is held down - if (false == Train->controlled->trainHeating.allow) + if (false == Train->controlled->trainHeating.IsAllowed()) { // turn on OnCommand_heatingenable(Train, Command); @@ -73,7 +73,7 @@ void TTrain::OnCommand_heatingtoggle(TTrain *Train, command_data const &Command) OnCommand_heatingdisable(Train, Command); } } - else if (Command.action == GLFW_RELEASE && (Train->ggTrainHeatingButton.type() == TGaugeType::push || Train->occupied->trainHeating.switchImpulse)) + else if (Command.action == GLFW_RELEASE && (Train->ggTrainHeatingButton.type() == TGaugeType::push || Train->occupied->trainHeating.config.switchImpulse)) { // impulse switch // visual feedback @@ -91,7 +91,7 @@ void TTrain::OnCommand_heatingenable(TTrain *Train, command_data const &Command) // visual feedback Train->ggTrainHeatingButton.UpdateValue(1.0, Train->dsbSwitch); } - else if (Command.action == GLFW_RELEASE && Train->occupied->trainHeating.switchImpulse) + else if (Command.action == GLFW_RELEASE && Train->occupied->trainHeating.config.switchImpulse) { // the switch springs back to the middle Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); @@ -107,7 +107,7 @@ void TTrain::OnCommand_heatingdisable(TTrain *Train, command_data const &Command Train->occupied->HeatingSwitch(false); // visual feedback: an impulse switch is pushed the other way, down auto position{0.0}; - if (Train->occupied->trainHeating.switchImpulse) + if (Train->occupied->trainHeating.config.switchImpulse) { position = -1.0; } @@ -117,7 +117,7 @@ void TTrain::OnCommand_heatingdisable(TTrain *Train, command_data const &Command } Train->ggTrainHeatingButton.UpdateValue(position, Train->dsbSwitch); } - else if (Command.action == GLFW_RELEASE && Train->occupied->trainHeating.switchImpulse) + else if (Command.action == GLFW_RELEASE && Train->occupied->trainHeating.config.switchImpulse) { Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); } diff --git a/vehicle/cab/pantographcommands.cpp b/vehicle/cab/pantographcommands.cpp index a1806c9d6..f41689591 100644 --- a/vehicle/cab/pantographcommands.cpp +++ b/vehicle/cab/pantographcommands.cpp @@ -73,7 +73,7 @@ void TTrain::OnCommand_pantographtogglefront(TTrain *Train, command_data const & else if (Command.action == GLFW_RELEASE) { // impulse switches return automatically to neutral position - if (Train->occupied->pantographCircuit.switchType == "impulse") + if (Train->occupied->pantographCircuit.config.switchType == "impulse") { auto const ismanual{Train->iCabn == 0}; Train->occupied->OperatePantographValve(VehicleEnd::front, operation_t::none, ismanual ? range_t::local : range_t::consist); @@ -107,7 +107,7 @@ void TTrain::OnCommand_pantographtogglerear(TTrain *Train, command_data const &C else if (Command.action == GLFW_RELEASE) { // impulse switches return automatically to neutral position - if (Train->occupied->pantographCircuit.switchType == "impulse") + if (Train->occupied->pantographCircuit.config.switchType == "impulse") { auto const ismanual{Train->iCabn == 0}; Train->occupied->OperatePantographValve(VehicleEnd::rear, operation_t::none, ismanual ? range_t::local : range_t::consist); @@ -134,7 +134,7 @@ void TTrain::OnCommand_pantographraisefront(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->occupied->OperatePantographValve(VehicleEnd::front, Train->occupied->pantographCircuit.switchType == "impulse" ? operation_t::enable_on : operation_t::enable, + Train->occupied->OperatePantographValve(VehicleEnd::front, Train->occupied->pantographCircuit.config.switchType == "impulse" ? operation_t::enable_on : operation_t::enable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -163,7 +163,7 @@ void TTrain::OnCommand_pantographraiserear(TTrain *Train, command_data const &Co // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->occupied->OperatePantographValve(VehicleEnd::rear, Train->occupied->pantographCircuit.switchType == "impulse" ? operation_t::enable_on : operation_t::enable, + Train->occupied->OperatePantographValve(VehicleEnd::rear, Train->occupied->pantographCircuit.config.switchType == "impulse" ? operation_t::enable_on : operation_t::enable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -182,7 +182,7 @@ void TTrain::OnCommand_pantographlowerfront(TTrain *Train, command_data const &C return; } // prevent operation without submodel outside of engine compartment - if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->occupied->pantographCircuit.switchType == "impulse" ? "pantfrontoff_sw:" : "pantfront_sw:")) + if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->occupied->pantographCircuit.config.switchType == "impulse" ? "pantfrontoff_sw:" : "pantfront_sw:")) { return; } @@ -192,7 +192,7 @@ void TTrain::OnCommand_pantographlowerfront(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->occupied->OperatePantographValve(VehicleEnd::front, Train->occupied->pantographCircuit.switchType == "impulse" ? operation_t::disable_on : operation_t::disable, + Train->occupied->OperatePantographValve(VehicleEnd::front, Train->occupied->pantographCircuit.config.switchType == "impulse" ? operation_t::disable_on : operation_t::disable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -211,7 +211,7 @@ void TTrain::OnCommand_pantographlowerrear(TTrain *Train, command_data const &Co return; } - if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->occupied->pantographCircuit.switchType == "impulse" ? "pantrearoff_sw:" : "pantrear_sw:")) + if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->occupied->pantographCircuit.config.switchType == "impulse" ? "pantrearoff_sw:" : "pantrear_sw:")) { return; } @@ -221,7 +221,7 @@ void TTrain::OnCommand_pantographlowerrear(TTrain *Train, command_data const &Co // only reacting to press, so the switch doesn't flip back and forth if key is held down // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers auto const ismanual{Train->iCabn == 0}; - Train->occupied->OperatePantographValve(VehicleEnd::rear, Train->occupied->pantographCircuit.switchType == "impulse" ? operation_t::disable_on : operation_t::disable, + Train->occupied->OperatePantographValve(VehicleEnd::rear, Train->occupied->pantographCircuit.config.switchType == "impulse" ? operation_t::disable_on : operation_t::disable, ismanual ? range_t::local : range_t::consist); } else if (Command.action == GLFW_RELEASE) @@ -254,9 +254,9 @@ void TTrain::OnCommand_pantographlowerall(TTrain *Train, command_data const &Com // two-state switch, only cares about press events if (Command.action == GLFW_PRESS) { - Train->pantographUnit->DropAllPantographs(false == Train->pantographUnit->pantographCircuit.allDown); + Train->pantographUnit->DropAllPantographs(false == Train->pantographUnit->pantographCircuit.AllDown()); // visual feedback - Train->ggPantAllDownButton.UpdateValue(Train->pantographUnit->pantographCircuit.allDown ? 1.0 : 0.0, Train->dsbSwitch); + Train->ggPantAllDownButton.UpdateValue(Train->pantographUnit->pantographCircuit.AllDown() ? 1.0 : 0.0, Train->dsbSwitch); } } else @@ -525,7 +525,7 @@ void TTrain::OnCommand_pantographcompressorvalvetoggle(TTrain *Train, command_da if (Command.action == GLFW_PRESS) { // only react to press - if (Train->controlled->pantographAir.connectedToMainReservoir == false) + if (Train->controlled->pantographAir.IsConnectedToMainReservoir() == false) { // connect pantographs with primary tank OnCommand_pantographcompressorvalveenable(Train, Command); @@ -552,7 +552,7 @@ void TTrain::OnCommand_pantographcompressorvalveenable(TTrain *Train, command_da { // only react to press // connect pantographs with primary tank - Train->controlled->pantographAir.connectedToMainReservoir = true; + Train->controlled->pantographAir.ConnectToMainReservoir(true); // visual feedback: Train->ggPantCompressorValve.UpdateValue(0.0); } @@ -572,7 +572,7 @@ void TTrain::OnCommand_pantographcompressorvalvedisable(TTrain *Train, command_d { // only react to press // connect pantograps with pantograph compressor - Train->controlled->pantographAir.connectedToMainReservoir = false; + Train->controlled->pantographAir.ConnectToMainReservoir(false); // visual feedback: Train->ggPantCompressorValve.UpdateValue(1.0); } @@ -590,10 +590,10 @@ void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data if (Command.action != GLFW_RELEASE) { // press or hold to activate - if (Train->pantographUnit->pantographAir.pressure < 4.8 && true == Train->pantographUnit->lowVoltage.power24vAvailable) + if (Train->pantographUnit->pantographAir.Pressure() < 4.8 && true == Train->pantographUnit->lowVoltage.Is24vAvailable()) { // needs live power source and low enough pressure to work - Train->pantographUnit->pantographAir.compressorRunning = true; + Train->pantographUnit->pantographAir.SwitchCompressor(true); } // visual feedback Train->ggPantCompressorButton.UpdateValue(1.0); @@ -601,7 +601,7 @@ void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data else { // release to disable - Train->pantographUnit->pantographAir.compressorRunning = false; + Train->pantographUnit->pantographAir.SwitchCompressor(false); // visual feedback Train->ggPantCompressorButton.UpdateValue(0.0); } diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index 47cc28267..c1cef46ad 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -888,7 +888,7 @@ void TTrain::set_cab_controls(int const Cab) { // switches // battery - ggBatteryButton.PutValue(ggBatteryButton.type() == TGaugeType::push ? 0.5f : occupied->lowVoltage.power24vAvailable ? 1.f : 0.f); + ggBatteryButton.PutValue(ggBatteryButton.type() == TGaugeType::push ? 0.5f : occupied->lowVoltage.Is24vAvailable() ? 1.f : 0.f); // activation ggCabActivationButton.PutValue(ggCabActivationButton.type() == TGaugeType::push ? 0.5f : occupied->IsCabMaster() ? 1.f : 0.f); // line breaker @@ -985,9 +985,9 @@ void TTrain::set_cab_controls(int const Cab) ggPantValvesButton.PutValue(0.5f); // auxiliary compressor - ggPantCompressorValve.PutValue(controlled->pantographAir.connectedToMainReservoir ? 0.f : // default setting is pantographs connected with primary tank + ggPantCompressorValve.PutValue(controlled->pantographAir.IsConnectedToMainReservoir() ? 0.f : // default setting is pantographs connected with primary tank 1.f); - ggPantCompressorButton.PutValue(pantographUnit->pantographAir.compressorRunning ? 1.f : 0.f); + ggPantCompressorButton.PutValue(pantographUnit->pantographAir.IsCompressorRunning() ? 1.f : 0.f); // converter if (occupied->converter.config.switchType != "impulse") { @@ -1077,9 +1077,9 @@ void TTrain::set_cab_controls(int const Cab) ggDoorStepButton.PutValue(occupied->Doors.step_enabled ? 1.f : 0.f); } // heating - if (false == ggTrainHeatingButton.is_push() && false == occupied->trainHeating.switchImpulse) + if (false == ggTrainHeatingButton.is_push() && false == occupied->trainHeating.config.switchImpulse) { - ggTrainHeatingButton.PutValue(controlled->trainHeating.on ? 1.f : 0.f); + ggTrainHeatingButton.PutValue(controlled->trainHeating.IsOn() ? 1.f : 0.f); } // brake acting time if (ggBrakeProfileCtrl.SubModel != nullptr) @@ -1340,7 +1340,7 @@ bool TTrain::initialize_button(cParser &Parser, std::string const &Label, int co {"i-doorpermit_any:", &m_doorpermits}, {"i-doorstep:", &occupied->Doors.step_enabled}, {"i-mainpipelock:", &occupied->brakes.pipeLock.locked}, - {"i-battery:", &occupied->lowVoltage.power24vAvailable}, + {"i-battery:", &occupied->lowVoltage.Is24vAvailable()}, {"i-cablight:", &Cabine[iCabn].bLight}, {"i-compartmentlights:", &occupied->CompartmentLights.is_active}, }; @@ -1845,7 +1845,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // manometr zbiornika kontrolnego/rorzďż˝du auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&pantographUnit->pantographAir.pressure); + gauge.AssignDouble(&pantographUnit->pantographAir.Pressure()); } else if (Label == "springbrakepress:") { @@ -1901,7 +1901,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // pantograph tank pressure auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&pantographUnit->pantographAir.pressure); + gauge.AssignDouble(&pantographUnit->pantographAir.Pressure()); } // yB - dla drugiej sekcji else if (Label == "hvbcurrent1:") diff --git a/vehicle/cab/sounds.cpp b/vehicle/cab/sounds.cpp index ebf928565..d893fd457 100644 --- a/vehicle/cab/sounds.cpp +++ b/vehicle/cab/sounds.cpp @@ -340,7 +340,7 @@ void TTrain::update_sounds(double const Deltatime) } // power-reliant sounds - if (occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable) + if (occupied->lowVoltage.Is24vAvailable() || occupied->lowVoltage.Is110vAvailable()) { // buzzer shp diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index c9581e0d2..2ea772fb8 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -173,14 +173,14 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("cabactive", occupied->CabActive); dict->insert("master", occupied->CabMaster); // basic systems state data - dict->insert("battery", occupied->lowVoltage.power24vAvailable); + dict->insert("battery", occupied->lowVoltage.Is24vAvailable()); dict->insert("linebreaker", controlled->lineBreaker.IsClosed()); dict->insert("main_init", controlled->lineBreaker.RemainingInitTime() < controlled->lineBreaker.config.initTime && controlled->lineBreaker.RemainingInitTime() > 0.0); dict->insert("main_ready", false == controlled->lineBreaker.IsClosed() && fHVoltage > 0.0 && controlled->lineBreaker.IsInitialised()); - dict->insert("converter", occupied->lowVoltage.power110vAvailable); + dict->insert("converter", occupied->lowVoltage.Is110vAvailable()); dict->insert("converter_overload", controlled->converter.IsOverloaded()); dict->insert("compress", controlled->air.compressor.running); - dict->insert("pant_compressor", pantographUnit->pantographAir.compressorRunning); + dict->insert("pant_compressor", pantographUnit->pantographAir.IsCompressorRunning()); dict->insert("lights_front", occupied->iLights[VehicleEnd::front]); dict->insert("lights_rear", occupied->iLights[VehicleEnd::rear]); dict->insert("off_from_dimmer", occupied->currentDimPosition().isOff); @@ -242,7 +242,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("ca", occupied->SecuritySystem.is_vigilance_blinking()); dict->insert("shp", occupied->SecuritySystem.is_cabsignal_blinking()); dict->insert("distance_counter", m_distancecounter); - dict->insert("pantpress", std::abs(pantographUnit->pantographAir.pressure)); + dict->insert("pantpress", std::abs(pantographUnit->pantographAir.Pressure())); dict->insert("universal3", InstrumentLightActive); for (auto idx = 0; idx < ggUniversals.size(); idx++) { @@ -267,7 +267,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("odometer", occupied->DistCounter); // distance run in the session, km dict->insert("odometer_total", occupied->Odometer.km); // the vehicle's odometer, kept between the sessions // electric current data - dict->insert("traction_voltage", std::abs(pantographUnit->pantographCircuit.supplyVoltage)); + dict->insert("traction_voltage", std::abs(pantographUnit->pantographCircuit.SupplyVoltage())); dict->insert("voltage", std::abs(controlled->EngineVoltage)); dict->insert("im", std::abs(controlled->Im)); dict->insert("fuse", controlled->FuseFlag); @@ -414,7 +414,7 @@ TTrain::state_t TTrain::get_state() const static_cast(occupied->air.mainReservoirPressure), static_cast(occupied->brakePipe.pressure), static_cast(occupied->brakes.cylinderPressure), - static_cast(pantographUnit->pantographAir.pressure), + static_cast(pantographUnit->pantographAir.Pressure()), fHVoltage, {fHCurrent[controlled->TrainType == train_type::emu ? 0 : 1], fHCurrent[2], fHCurrent[3]}, ggLVoltage.GetValue(), @@ -429,7 +429,7 @@ TTrain::state_t TTrain::get_state() const occupied->Doors.instances[occupied->CabOccupied < 0 ? VehicleSide::left : VehicleSide::right].open_permit, occupied->Doors.instances[occupied->CabOccupied < 0 ? VehicleSide::left : VehicleSide::right].is_open, occupied->Doors.step_enabled, - occupied->lowVoltage.power24vAvailable, + occupied->lowVoltage.Is24vAvailable(), 0, occupied->brakes.pipeLock.locked, btLampkaRadioMessage.GetValue(), @@ -439,7 +439,7 @@ TTrain::state_t TTrain::get_state() const bool TTrain::is_eztoer() const { - return controlled->TrainType == train_type::emu && occupied->brakes.subsystem == TBrakeSubSystem::ss_ESt && controlled->lowVoltage.power24vAvailable == true && controlled->EpFuse == true && + return controlled->TrainType == train_type::emu && occupied->brakes.subsystem == TBrakeSubSystem::ss_ESt && controlled->lowVoltage.Is24vAvailable() == true && controlled->EpFuse == true && controlled->DirActive != 0; // od yB } @@ -562,7 +562,7 @@ void TTrain::UpdateCab() void TTrain::add_distance(double const Distance) { - auto const meterenabled{m_distancecounter >= 0 && (occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable)}; + auto const meterenabled{m_distancecounter >= 0 && (occupied->lowVoltage.Is24vAvailable() || occupied->lowVoltage.Is110vAvailable())}; if (true == meterenabled) { diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 86e2281ee..34bb1a9df 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -65,7 +65,7 @@ bool TTrain::Update(double const Deltatime) updateUnitStates(); updateFeedbackGauges(); updateConverterOverload(Deltatime); - auto const lowvoltagepower{occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable}; + auto const lowvoltagepower{occupied->lowVoltage.Is24vAvailable() || occupied->lowVoltage.Is110vAvailable()}; updateSecondUnitGauges(); updateClock(); @@ -122,12 +122,12 @@ bool TTrain::Update(double const Deltatime) } // update direction relay - if (prevBatState != occupied->lowVoltage.power24vAvailable) + if (prevBatState != occupied->lowVoltage.Is24vAvailable()) SetupDirectionRelays(); if (prevDirection != occupied->DirActive) UpdateDirectionRelays(); - prevBatState = occupied->lowVoltage.power24vAvailable; + prevBatState = occupied->lowVoltage.Is24vAvailable(); prevDirection = occupied->DirActive; // sounds @@ -361,7 +361,7 @@ void TTrain::updateVoltagesAndCurrents() // Ra 2014-09: napięcia i prądy muszą być ustalone najpierw, bo wysyłane są ewentualnie na PoKeys if (controlled->EngineType != TEngineType::DieselElectric && controlled->EngineType != TEngineType::ElectricInductionMotor) { // Ra 2014-09: czy taki rozdzia? ma sens? - fHVoltage = static_cast(std::max(controlled->pantographCircuit.supplyVoltage, + fHVoltage = static_cast(std::max(controlled->pantographCircuit.SupplyVoltage(), controlled->GetTrainsetHighVoltage())); // Winger czy to nie jest zle? } // *controlled->Mains); @@ -483,11 +483,11 @@ void TTrain::updateUnitStates() fEIMParams[1 + in][9] = static_cast(p->physics->EngineVoltage); fEIMParams[0][6] += fEIMParams[1 + in][8]; bMains[in] = p->physics->lineBreaker.IsClosed(); - fCntVol[in] = static_cast(p->physics->lowVoltage.batteryVoltage); + fCntVol[in] = static_cast(p->physics->lowVoltage.BatteryVoltage()); bFuse[in] = p->physics->FuseFlag; - bBatt[in] = p->physics->lowVoltage.batteryOn; + bBatt[in] = p->physics->lowVoltage.IsBatteryOn(); bConv[in] = p->physics->converter.IsRunning(); - bHeat[in] = p->physics->trainHeating.on; + bHeat[in] = p->physics->trainHeating.IsOn(); // bComp[in][2] = (p->physics->CompressorAllow || (p->physics->CompressorStart == start_t::automatic)); // bComp[in][3] = (p->physics->CompressorFlag); in++; @@ -506,11 +506,11 @@ void TTrain::updateUnitStates() fDieselParams[1 + in][8] = p->physics->diesel.heat.Ts; fDieselParams[1 + in][9] = static_cast(p->physics->retarder.fill); bMains[in] = p->physics->lineBreaker.IsClosed(); - fCntVol[in] = static_cast(p->physics->lowVoltage.batteryVoltage); + fCntVol[in] = static_cast(p->physics->lowVoltage.BatteryVoltage()); bFuse[in] = p->physics->FuseFlag; - bBatt[in] = p->physics->lowVoltage.batteryOn; + bBatt[in] = p->physics->lowVoltage.IsBatteryOn(); bConv[in] = p->physics->converter.IsRunning(); - bHeat[in] = p->physics->trainHeating.on; + bHeat[in] = p->physics->trainHeating.IsOn(); in++; iPowerNo = in; } @@ -725,7 +725,7 @@ void TTrain::updateEngineGauges() { // NOTE: since we don't have functional converter object, we're faking it here by simple check whether converter is on // TODO: implement object-based circuits and power systems model so we can have this working more properly - ggLVoltage.UpdateValue(static_cast(std::max(occupied->lowVoltage.power110vAvailable ? occupied->lowVoltage.nominalBatteryVoltage : 0.0, occupied->lowVoltage.power24vAvailable ? occupied->lowVoltage.batteryVoltage : 0.0))); + ggLVoltage.UpdateValue(static_cast(std::max(occupied->lowVoltage.Is110vAvailable() ? occupied->lowVoltage.config.nominalBatteryVoltage : 0.0, occupied->lowVoltage.Is24vAvailable() ? occupied->lowVoltage.BatteryVoltage() : 0.0))); ggLVoltage.Update(); } @@ -798,7 +798,7 @@ void TTrain::updateBasicLamps() btCabActived.Turn(false); } - if (controlled->lowVoltage.batteryOn && controlled->CabActive != 0) + if (controlled->lowVoltage.IsBatteryOn() && controlled->CabActive != 0) btAKLVents.Turn(true); else btAKLVents.Turn(false); @@ -831,8 +831,8 @@ void TTrain::updateCircuitLamps(double const Deltatime) btLampkaMainBreakerReady.Turn(controlled->lineBreaker.IsInitialised() && m_linebreakerstate != linebreaker::state::closing && !controlled->lineBreaker.IsClosed()); btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || controlled->lineBreaker.IsClosed() || controlled->lineBreaker.RemainingInitTime() < 0.0 && simulation::Time.data().wMilliseconds > 500); - btLampkaPrzetw.Turn(occupied->lowVoltage.power110vAvailable); - btLampkaPrzetwOff.Turn(!occupied->lowVoltage.power110vAvailable); + btLampkaPrzetw.Turn(occupied->lowVoltage.Is110vAvailable()); + btLampkaPrzetwOff.Turn(!occupied->lowVoltage.Is110vAvailable()); btLampkaPrzetwAOff.Turn(!controlled->converter.IsRunning()); btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : controlled->converter.IsOverloaded()); @@ -1374,7 +1374,7 @@ void TTrain::updateHeatingAndInstrumentLights() { //--------- // hunter-080812: poprawka na ogrzewanie w elektrykach - usuniete uzaleznienie od przetwornicy - if (controlled->trainHeating.on == true && controlled->converter.IsOverloaded() == false) + if (controlled->trainHeating.IsOn() == true && controlled->converter.IsOverloaded() == false) btLampkaOgrzewanieSkladu.Turn(true); else btLampkaOgrzewanieSkladu.Turn(false); @@ -1382,11 +1382,11 @@ void TTrain::updateHeatingAndInstrumentLights() //---------- // lights - auto const lightpower{(InstrumentLightType == 0 ? occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable : + auto const lightpower{(InstrumentLightType == 0 ? occupied->lowVoltage.Is24vAvailable() || occupied->lowVoltage.Is110vAvailable() : InstrumentLightType == 1 ? controlled->lineBreaker.IsClosed() : - InstrumentLightType == 2 ? occupied->lowVoltage.power110vAvailable : - InstrumentLightType == 3 ? occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable : - InstrumentLightType == 4 ? occupied->lowVoltage.power24vAvailable || occupied->lowVoltage.power110vAvailable : + InstrumentLightType == 2 ? occupied->lowVoltage.Is110vAvailable() : + InstrumentLightType == 3 ? occupied->lowVoltage.Is24vAvailable() || occupied->lowVoltage.Is110vAvailable() : + InstrumentLightType == 4 ? occupied->lowVoltage.Is24vAvailable() || occupied->lowVoltage.Is110vAvailable() : false)}; InstrumentLightActive = InstrumentLightType == 3 ? true : // TODO: link the light state with the state of the master key InstrumentLightType == 4 ? occupied->iLights[VehicleEnd::front] != 0 || occupied->iLights[VehicleEnd::rear] != 0 : @@ -1574,7 +1574,7 @@ void TTrain::updateCabLightLevels() for (auto &cab : Cabine) { - auto const cablightlevel = (cab.bLight == false ? 0.f : cab.bLightDim == true ? 0.4f : 1.f) * (occupied->lowVoltage.power110vAvailable ? 1.f : 0.5f); + auto const cablightlevel = (cab.bLight == false ? 0.f : cab.bLightDim == true ? 0.4f : 1.f) * (occupied->lowVoltage.Is110vAvailable() ? 1.f : 0.5f); if (cab.LightLevel != cablightlevel) { @@ -1593,21 +1593,21 @@ void TTrain::updateCabLightLevels() void TTrain::UpdateDirectionRelays() { - if (occupied->DirActive < 0 && occupied->lowVoltage.power24vAvailable) // wstecz + if (occupied->DirActive < 0 && occupied->lowVoltage.Is24vAvailable()) // wstecz Dynamic()->sDirectionRelayR.play(); - if (occupied->DirActive == 0 && occupied->lowVoltage.power24vAvailable) // neutral + if (occupied->DirActive == 0 && occupied->lowVoltage.Is24vAvailable()) // neutral Dynamic()->sDirectionRelayN.play(); - if (occupied->DirActive > 0 && occupied->lowVoltage.power24vAvailable) // przod + if (occupied->DirActive > 0 && occupied->lowVoltage.Is24vAvailable()) // przod Dynamic()->sDirectionRelayD.play(); } void TTrain::SetupDirectionRelays() { - if (occupied->lowVoltage.power24vAvailable) + if (occupied->lowVoltage.Is24vAvailable()) { - if (occupied->DirActive < 0 && occupied->lowVoltage.power24vAvailable) // wstecz + if (occupied->DirActive < 0 && occupied->lowVoltage.Is24vAvailable()) // wstecz Dynamic()->sDirectionRelayR.play(); - if (occupied->DirActive > 0 && occupied->lowVoltage.power24vAvailable) // przod + if (occupied->DirActive > 0 && occupied->lowVoltage.Is24vAvailable()) // przod Dynamic()->sDirectionRelayD.play(); } else if (occupied->DirActive != 0) // neutral diff --git a/vehicle/dynamic/destinations.cpp b/vehicle/dynamic/destinations.cpp index 6311c8799..556629ed2 100644 --- a/vehicle/dynamic/destinations.cpp +++ b/vehicle/dynamic/destinations.cpp @@ -106,7 +106,7 @@ void TDynamicObject::update_destinations() { if( DestinationSign.sign == nullptr ) { return; } - auto const lowvoltagepower { ( physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable ) }; + auto const lowvoltagepower { ( physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable() ) }; DestinationSign.sign->fLight = DestinationSign.has_light && lowvoltagepower ? 2.0 : -1.0; diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index ddd6816e5..b3c7ed654 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -354,8 +354,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" physics->brakePipe.pressure = 0.0; physics->mainPipe.reservoir->CreatePress(0.0); physics->mainPipe.pressure = 0.0; - physics->pantographAir.volume = 0.1; - physics->pantographAir.pressure = 0.0; + physics->pantographAir.Empty(); physics->air.compressedVolume = 0.0; } diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index ca0f4b863..31ea07e97 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -117,7 +117,7 @@ void TDynamicObject::renderAuxiliarySounds() { // NBMX dzwiek przetwornicy if( physics->converter.IsRunning() ) { if( physics->EngineType == TEngineType::ElectricSeriesMotor ) { - auto const voltage { std::max( physics->GetTrainsetHighVoltage(), physics->pantographCircuit.supplyVoltage ) }; + auto const voltage { std::max( physics->GetTrainsetHighVoltage(), physics->pantographCircuit.SupplyVoltage() ) }; if( voltage > 0.0 ) { // NOTE: we do sound modulation here to avoid sudden jump on voltage loss frequency = voltage / (physics->NominalVoltage * physics->RList[physics->RlistSize].Mn); @@ -187,7 +187,7 @@ void TDynamicObject::renderAuxiliarySounds() { } // Winger 160404 - dzwiek malej sprezarki - if( physics->pantographAir.compressorRunning ) { + if( physics->pantographAir.IsCompressorRunning() ) { sSmallCompressor.play( sound_flags::exclusive | sound_flags::looping ); } else { @@ -197,7 +197,7 @@ void TDynamicObject::renderAuxiliarySounds() { // heater sound { auto const isdieselenginepowered { physics->EngineType == TEngineType::DieselElectric || physics->EngineType == TEngineType::DieselEngine }; - if( true == physics->trainHeating.on + if( true == physics->trainHeating.IsOn() && ( false == isdieselenginepowered || std::abs(physics->enrot) > 0.01 ) ) { sHeater @@ -212,7 +212,7 @@ void TDynamicObject::renderAuxiliarySounds() { } // battery sound - if( physics->lowVoltage.batteryOn ) { + if( physics->lowVoltage.IsBatteryOn() ) { m_batterysound.play( sound_flags::exclusive | sound_flags::looping ); } else { @@ -487,7 +487,7 @@ void TDynamicObject::renderDepartureSignalSounds() { // NBMX sygnal odjazdu if( physics->Doors.has_warning ) { - auto const lowvoltagepower { physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable }; + auto const lowvoltagepower { physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable() }; for( auto &doorspeaker : m_doorspeakers ) { // TBD, TODO: per-location door state triggers? if( physics->DepartureSignal @@ -514,7 +514,7 @@ void TDynamicObject::renderAnnouncementSounds() { // announcements { - auto const lowvoltagepower { physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable }; + auto const lowvoltagepower { physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable() }; if( lowvoltagepower ) { // system is powered up, can play queued announcements if( false == m_pasystem.announcement_queue.empty() diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index d859d7674..1b65057ff 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -257,7 +257,7 @@ void TDynamicObject::updateTractionVoltage( double const dt1 ) // napiecie sieci trakcyjnej if (physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { // dla EZT tylko silnikowy - tmpTraction.TractionVoltage = std::max( std::abs( physics->pantographCircuit.rearVoltage ), std::abs( physics->pantographCircuit.frontVoltage ) ); + tmpTraction.TractionVoltage = std::max( std::abs( physics->pantographCircuit.RearVoltage() ), std::abs( physics->pantographCircuit.FrontVoltage() ) ); // jeśli brak zasilania dłużej niż 0.2 sekundy (25km/h pod izolatorem daje 0.15s) // Ra 2F1H: prowizorka, trzeba przechować napięcie, żeby nie wywalało WS pod izolatorem if( tmpTraction.TractionVoltage > 0.0) { @@ -266,7 +266,7 @@ void TDynamicObject::updateTractionVoltage( double const dt1 ) else { NoVoltTime += dt1; if( NoVoltTime <= 0.2 ) { - tmpTraction.TractionVoltage = physics->pantographCircuit.supplyVoltage; + tmpTraction.TractionVoltage = physics->pantographCircuit.SupplyVoltage(); } else { // jeśli jedzie @@ -295,7 +295,7 @@ void TDynamicObject::updateTractionVoltage( double const dt1 ) tmpTraction.TractionMaxCurrent = 7500; // Ra: chyba za dużo? powinno wywalać przy 1500 tmpTraction.TractionResistivity = 0.3; - physics->pantographCircuit.supplyVoltage = tmpTraction.TractionVoltage; + physics->pantographCircuit.SetSupplyVoltage(tmpTraction.TractionVoltage); } // the driver of the vehicle: the integrated controller, the brakes blended over a consist with induction motors, the AI @@ -735,7 +735,7 @@ void TDynamicObject::switchOffMainsWithoutBattery() { // fragment "z EXE Kursa" if( physics->lineBreaker.IsClosed() ) { // nie wchodzić w funkcję bez potrzeby - if( false == (physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable) + if( false == (physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable()) /* // NOTE: disabled on account of multi-unit setups, where the unmanned unit wouldn't be affected && ( Controller == Humandriver ) @@ -1037,8 +1037,8 @@ void TDynamicObject::updateCurrentCollectors( double const dt1 ) if (physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && physics->EnginePowerSource.CollectorParameters.FakePower) { - physics->pantographCircuit.rearVoltage = 0.95 * physics->EnginePowerSource.MaxVoltage; - physics->pantographCircuit.frontVoltage = 0.95 * physics->EnginePowerSource.MaxVoltage; + physics->pantographCircuit.SetRearVoltage(0.95 * physics->EnginePowerSource.MaxVoltage); + physics->pantographCircuit.SetFrontVoltage(0.95 * physics->EnginePowerSource.MaxVoltage); } } @@ -1059,9 +1059,9 @@ void TDynamicObject::updatePantograph( int const i, double const fPantCurrent, d if (p->fAngleU > M_PI) p->fAngleU = M_PI; if (i & 1) // zgłoszono, że po połamaniu potrafi zostać zasilanie - physics->pantographCircuit.rearVoltage = 0.0; + physics->pantographCircuit.SetRearVoltage(0.0); else - physics->pantographCircuit.frontVoltage = 0.0; + physics->pantographCircuit.SetFrontVoltage(0.0); return; // reszta wtedy nie jest wykonywana } PantDiff = p->PantTraction - p->PantWys; // docelowy-aktualny @@ -1078,30 +1078,29 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d if (Global.bLiveTraction == false && p->hvPowerWire == nullptr ) { // jeśli nie ma drutu, może pooszukiwać - physics->pantographCircuit.frontVoltage = - p->PantWys >= 1.2 ? + physics->pantographCircuit.SetFrontVoltage(p->PantWys >= 1.2 ? 0.95 * physics->EnginePowerSource.MaxVoltage : - 0.0; + 0.0); } else if( true == physics->pantographs[VehicleEnd::front].is_active && PantDiff < 0.01 ) // tolerancja niedolegania { if (p->hvPowerWire) { - auto const lastvoltage { physics->pantographCircuit.frontVoltage }; + auto const lastvoltage { physics->pantographCircuit.FrontVoltage() }; // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() if( lastvoltage == 0.0 ) { // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply - physics->pantographCircuit.frontVoltage = p->hvPowerWire->VoltageGet( physics->pantographCircuit.supplyVoltage, 0.0 ); + physics->pantographCircuit.SetFrontVoltage(p->hvPowerWire->VoltageGet( physics->pantographCircuit.SupplyVoltage(), 0.0 )); } else { - physics->pantographCircuit.frontVoltage = p->hvPowerWire->VoltageGet( physics->pantographCircuit.supplyVoltage, fPantCurrent ); - if( physics->pantographCircuit.frontVoltage > 0.0 ) { + physics->pantographCircuit.SetFrontVoltage(p->hvPowerWire->VoltageGet( physics->pantographCircuit.SupplyVoltage(), fPantCurrent )); + if( physics->pantographCircuit.FrontVoltage() > 0.0 ) { fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) } } // TODO: refactor reaction to voltage change to physics as sound event for specific pantograph if( lastvoltage == 0.0 - && physics->pantographCircuit.frontVoltage > 0.0 ) { + && physics->pantographCircuit.FrontVoltage() > 0.0 ) { for( auto &pantograph : m_pantographsounds ) { if( pantograph.sPantUp.offset().z > 0 ) { // limit to pantographs located in the front half of the vehicle @@ -1111,40 +1110,39 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d } } else - physics->pantographCircuit.frontVoltage = 0.0; + physics->pantographCircuit.SetFrontVoltage(0.0); } else - physics->pantographCircuit.frontVoltage = 0.0; - ( fPantCurrent > 0.0 ? physics->EnergyMeter.first : physics->EnergyMeter.second ) += physics->pantographCircuit.frontVoltage * fPantCurrent * dt1 / 3600000.0; + physics->pantographCircuit.SetFrontVoltage(0.0); + ( fPantCurrent > 0.0 ? physics->EnergyMeter.first : physics->EnergyMeter.second ) += physics->pantographCircuit.FrontVoltage() * fPantCurrent * dt1 / 3600000.0; break; case 1: if( false == Global.bLiveTraction && nullptr == p->hvPowerWire ) { // jeśli nie ma drutu, może pooszukiwać - physics->pantographCircuit.rearVoltage = - p->PantWys >= 1.2 ? + physics->pantographCircuit.SetRearVoltage(p->PantWys >= 1.2 ? 0.95 * physics->EnginePowerSource.MaxVoltage : - 0.0; + 0.0); } else if ( true == physics->pantographs[VehicleEnd::rear].is_active && PantDiff < 0.01 ) { if (p->hvPowerWire) { - auto const lastvoltage { physics->pantographCircuit.rearVoltage }; + auto const lastvoltage { physics->pantographCircuit.RearVoltage() }; // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() if( lastvoltage == 0.0 ) { // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply - physics->pantographCircuit.rearVoltage = p->hvPowerWire->VoltageGet( physics->pantographCircuit.supplyVoltage, 0.0 ); + physics->pantographCircuit.SetRearVoltage(p->hvPowerWire->VoltageGet( physics->pantographCircuit.SupplyVoltage(), 0.0 )); } else { - physics->pantographCircuit.rearVoltage = p->hvPowerWire->VoltageGet( physics->pantographCircuit.supplyVoltage, fPantCurrent ); - if( physics->pantographCircuit.rearVoltage > 0.0 ) { + physics->pantographCircuit.SetRearVoltage(p->hvPowerWire->VoltageGet( physics->pantographCircuit.SupplyVoltage(), fPantCurrent )); + if( physics->pantographCircuit.RearVoltage() > 0.0 ) { fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) } } // TODO: refactor reaction to voltage change to physics as sound event for specific pantograph if( lastvoltage == 0.0 - && physics->pantographCircuit.rearVoltage > 0.0 ) { + && physics->pantographCircuit.RearVoltage() > 0.0 ) { for( auto &pantograph : m_pantographsounds ) { if( pantograph.sPantUp.offset().z < 0 ) { // limit to pantographs located in the rear half of the vehicle @@ -1154,13 +1152,13 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d } } else - physics->pantographCircuit.rearVoltage = 0.0; + physics->pantographCircuit.SetRearVoltage(0.0); } else { // Global.iPause ^= 2; - physics->pantographCircuit.rearVoltage = 0.0; + physics->pantographCircuit.SetRearVoltage(0.0); } - ( fPantCurrent > 0.0 ? physics->EnergyMeter.first : physics->EnergyMeter.second ) += physics->pantographCircuit.rearVoltage * fPantCurrent * dt1 / 3600000.0; + ( fPantCurrent > 0.0 ? physics->EnergyMeter.first : physics->EnergyMeter.second ) += physics->pantographCircuit.RearVoltage() * fPantCurrent * dt1 / 3600000.0; break; } // pozostałe na razie nie obsługiwane } @@ -1169,18 +1167,18 @@ void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, d void TDynamicObject::updatePantographMotion( int const i, TAnimPant *p, double const PantDiff, double const dt1 ) { double k; // tymczasowy kąt - if( physics->pantographAir.pressure > ( + if( physics->pantographAir.Pressure() > ( physics->TrainType == train_type::emu ? 2.45 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 3.45 ) ) { // z EXE Kursa // Ra: wysokość zależy od ciśnienia !!! - pantspeedfactor = 0.015 * physics->pantographAir.pressure * dt1; + pantspeedfactor = 0.015 * physics->pantographAir.Pressure() * dt1; } else { pantspeedfactor = 0.0; } - if( false == ( physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable ) ) { + if( false == ( physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable() ) ) { pantspeedfactor = 0.0; } pantspeedfactor = std::max( 0.0, pantspeedfactor ); @@ -1282,12 +1280,12 @@ void TDynamicObject::updateWipers( double const dt1 ) // rozroznienie kabinowe if (physics->CabActive == 1) { - wipersActive = (bytesum & 1 << i) != 0 && physics->lowVoltage.batteryOn; + wipersActive = (bytesum & 1 << i) != 0 && physics->lowVoltage.IsBatteryOn(); } else if (physics->CabActive == -1) { // odwroconie indexow wycieraczek - wipersActive = (bytesum & 1 << dWiperPos.size() - 1 - i) != 0 && physics->lowVoltage.batteryOn; + wipersActive = (bytesum & 1 << dWiperPos.size() - 1 - i) != 0 && physics->lowVoltage.IsBatteryOn(); } else { wipersActive = false; diff --git a/vehicle/dynamic/visual.cpp b/vehicle/dynamic/visual.cpp index 52be7d914..8e322cc02 100644 --- a/vehicle/dynamic/visual.cpp +++ b/vehicle/dynamic/visual.cpp @@ -346,7 +346,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } // else btCPass2.TurnOff(); - if (physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable) + if (physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable()) { // sygnaly konca pociagu if (m_endsignals1.Active()) { if (TestFlag(physics->iLights[VehicleEnd::front], light::redmarker_left | light::redmarker_right ) ) { @@ -441,7 +441,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } // vehicle within 400m - if( physics->lowVoltage.power24vAvailable || physics->lowVoltage.power110vAvailable ) + if( physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable() ) { // sygnały czoła pociagu //Ra: wyświetlamy bez // ograniczeń odległości, by były widoczne z // daleka diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index ecada0130..57c66c7d2 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -68,7 +68,7 @@ void ui::vehicleparams_panel::draw_mini(const physics::Vehicle &physics) if (physics.pantographs[VehicleEnd::front].is_active) draw_infobutton("╨╨╨", ImVec2(290, 10)); - if (physics.lowVoltage.batteryOn) + if (physics.lowVoltage.IsBatteryOn()) draw_infobutton(STR_C("bat."), ImVec2(120, 55)); if (physics.lineBreaker.IsClosed()) draw_infobutton(STR_C("main.")); @@ -148,8 +148,8 @@ void ui::vehicleparams_panel::render_contents() std::snprintf(buffer.data(), buffer.size(), STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s%s%s%.0f@%.0f"), // devices - (physics.lowVoltage.batteryOn ? 'B' : '.'), (physics.lineBreaker.IsClosed() ? 'M' : '.'), (physics.FuseFlag ? '!' : '.'), (physics.pantographs[VehicleEnd::rear].is_active ? (physics.pantographCircuit.rearVoltage > 0.0 ? 'O' : 'o') : '.'), - (physics.pantographs[VehicleEnd::front].is_active ? (physics.pantographCircuit.frontVoltage > 0.0 ? 'P' : 'p') : '.'), (physics.pantographAir.pressureLockActive ? '!' : (physics.pantographAir.pressureSwitchActive ? '*' : '.')), + (physics.lowVoltage.IsBatteryOn() ? 'B' : '.'), (physics.lineBreaker.IsClosed() ? 'M' : '.'), (physics.FuseFlag ? '!' : '.'), (physics.pantographs[VehicleEnd::rear].is_active ? (physics.pantographCircuit.RearVoltage() > 0.0 ? 'O' : 'o') : '.'), + (physics.pantographs[VehicleEnd::front].is_active ? (physics.pantographCircuit.FrontVoltage() > 0.0 ? 'P' : 'p') : '.'), (physics.pantographAir.IsPressureLockActive() ? '!' : (physics.pantographAir.IsPressureSwitchPrimed() ? '*' : '.')), (physics.WaterPump.is_active ? 'W' : (false == physics.WaterPump.breaker ? '-' : (physics.WaterPump.is_enabled ? 'w' : '.'))), (true == physics.WaterHeater.is_damaged ? '!' : (physics.WaterHeater.is_active ? 'H' : (false == physics.WaterHeater.breaker ? '-' : (physics.WaterHeater.is_enabled ? 'h' : '.')))), (physics.FuelPump.is_active ? 'F' : (physics.FuelPump.is_enabled ? 'f' : '.')), (physics.OilPump.is_active ? 'O' : (physics.OilPump.is_enabled ? 'o' : '.')), @@ -213,7 +213,7 @@ void ui::vehicleparams_panel::render_contents() if (physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { - std::snprintf(buffer.data(), buffer.size(), STR_C(" pantograph: %.2f%cMT"), physics.pantographAir.pressure, (physics.pantographAir.connectedToMainReservoir ? '-' : '|')); + std::snprintf(buffer.data(), buffer.size(), STR_C(" pantograph: %.2f%cMT"), physics.pantographAir.Pressure(), (physics.pantographAir.IsConnectedToMainReservoir() ? '-' : '|')); ImGui::TextUnformatted(buffer.data()); } From 1eaca10ac9ac753d960652a7db609fcaad3466b8 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 29 Nov 2026 10:12:35 +0100 Subject: [PATCH 09/30] test(scenarios): baltyk_skm1 cases follow the new units of their missions SVN r9644 (2026-11-15) put an EN57AL-1230ra in mission ROJ55321 instead of EN71-014ra and an ED78-019A in ROJ55324 instead of EN90-009A, so both cases ended at once with "the scenery has no vehicle" (exit code 14). The cases now test the new units; both pass on staging b7f2186a1. --- tests/scenarios/README.md | 4 ++-- tests/scenarios/cases/baltyk_skm1_roj55321_departure.json | 4 ++-- .../scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/scenarios/README.md b/tests/scenarios/README.md index 529fefea6..40c189c66 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -613,8 +613,8 @@ 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 | +| `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. Since SVN r9644 (2026-11-15) the mission's unit is ED78-019A instead of EN90-009A; with it the case passes on staging b7f2186a1 (one seed) | +| `baltyk_skm1_roj55321_departure` | #525 | passes, with three seeds: the unit in the platform leaves at 10:34. Since SVN r9644 (2026-11-15) the mission's unit is EN57AL-1230ra instead of EN71-014ra; with it the case passes on staging b7f2186a1 (one seed) | | `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 | diff --git a/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json b/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json index 98b9c8119..3a820f17a 100644 --- a/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json +++ b/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json @@ -1,8 +1,8 @@ { - "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.", + "description": "eu07/maszyna#525, Baltyk skm1, the mission that starts in the platform of Baltyk Glowny (EN57AL-1230ra, ROJ55321, departure 10:34; the EN71 of this mission became an EN57AL in SVN r9644): 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", + "vehicle": "EN57AL-1230ra", "slow": true, "physicslog": false, "ini": [ diff --git a/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json b/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json index a8fa0e7cc..343b431d4 100644 --- a/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json +++ b/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json @@ -1,8 +1,8 @@ { - "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.", + "description": "eu07/maszyna#525, Baltyk skm1, the mission that starts on the siding of Baltyk Towarowy next to the shunter (ED78-019A, ROJ55324; the EN90 of this mission became an ED78 in SVN r9644): 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", + "vehicle": "ED78-019A", "slow": true, "physicslog": false, "ini": [ From bc2af26dd51179f6553e60569d1c4e93c88a4b89 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 10:14:37 +0100 Subject: [PATCH 10/30] refactor(physics): the compressed air supply and the pipes keep their state to themselves The compressor, the main reservoir and the pipes along the train (physics/components/airsupply.h) become classes, as the parts of the main circuit: the definition in `config`, the state behind queries and operations. The step of the compressor (the programmer of a unit, its supply and its start delay, the governor and its lock, the venting over the top pressure) moves into AirCompressor::Update(), with what it needs from the vehicle as plain values (CompressorInputs); the vehicle follows the step up as before (the switching delay, the counter of the debug panel, the sound of the relay). The leaks and the pressure of the main reservoir move into AirSupply, and the reservoir is filled and drawn through it. The fault of the compressor the scenery can set no longer adds 100000001 to its pressures from TDynamicObject::Damage(): AirCompressor::SetFault() does the same arithmetic, so a fault behaves exactly as it did. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- application/driverhints.cpp | 2 +- application/driveruipanels.cpp | 16 +- input/messaging.cpp | 8 +- physics/components/airsupply.h | 312 ++++++++++++++++-- physics/components/body.cpp | 22 +- physics/components/cab.cpp | 8 +- physics/components/commands.cpp | 2 +- physics/components/controllers.cpp | 4 +- physics/components/drive.cpp | 2 +- physics/components/electrics.cpp | 2 +- physics/components/fizparser.cpp | 2 +- physics/components/fizsections.cpp | 46 +-- physics/components/pneumatics.cpp | 278 ++++++---------- physics/components/setup.cpp | 33 +- physics/components/traction.cpp | 2 +- physics/vehicle.h | 4 +- simulation/blackboxrecorder.cpp | 8 +- simulation/simulation.cpp | 2 +- tests/unit/consist.cpp | 2 +- tests/unit/drive.cpp | 6 +- tests/unit/figures.cpp | 2 +- tests/unit/golden.cpp | 18 +- tests/unit/invariants.cpp | 16 +- tests/unit/test_brake_handles.cpp | 18 +- tests/unit/test_brake_pipe.cpp | 10 +- tests/unit/test_brakes.cpp | 4 +- tests/unit/test_cab.cpp | 8 +- tests/unit/test_camshaft.cpp | 2 +- tests/unit/test_commands.cpp | 8 +- tests/unit/test_compressor.cpp | 68 ++-- tests/unit/test_controls.cpp | 16 +- tests/unit/test_crew.cpp | 4 +- tests/unit/test_definition.cpp | 36 +- tests/unit/test_dynamic_brake_diesel.cpp | 2 +- tests/unit/test_elf_controller.cpp | 26 +- tests/unit/test_feed_pipe.cpp | 24 +- tests/unit/test_figures.cpp | 8 +- tests/unit/test_genset.cpp | 2 +- tests/unit/test_horn.cpp | 24 +- tests/unit/test_line_contactors.cpp | 2 +- tests/unit/test_line_contactors_interlock.cpp | 12 +- tests/unit/test_mains_before_pantographs.cpp | 24 +- tests/unit/test_pressure_switch.cpp | 18 +- tests/unit/test_pullee.cpp | 24 +- tests/unit/vehicle.cpp | 8 +- vehicle/ai/consist.cpp | 24 +- vehicle/ai/engine.cpp | 6 +- vehicle/ai/force.cpp | 8 +- vehicle/ai/physicslog.cpp | 4 +- vehicle/ai/situation.cpp | 2 +- vehicle/cab/auxiliarycommands.cpp | 40 +-- vehicle/cab/setup.cpp | 12 +- vehicle/cab/train.cpp | 10 +- vehicle/cab/update.cpp | 30 +- vehicle/dynamic/consist.cpp | 6 +- vehicle/dynamic/lifecycle.cpp | 6 +- vehicle/dynamic/sounds.cpp | 10 +- vehicle/dynamic/update.cpp | 15 +- vehicle/dynamic/vehicletable.cpp | 6 +- widgets/vehicleparams.cpp | 10 +- 60 files changed, 731 insertions(+), 603 deletions(-) diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 7336b18dd..d84e663df 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -752,7 +752,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvControlling->mainPipe.pressure > 4.5 || mvControlling->air.mainReservoirVolume == 0.0; } ); + return mvControlling->mainPipe.Pressure() > 4.5 || mvControlling->air.config.mainReservoirVolume == 0.0; } ); break; } case driver_hint::waitpantographpressuretoolow: { diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 6ddc9aa4f..6533dcbbc 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -150,7 +150,7 @@ drivingaid_panel::update() { m_buffer.data(), m_buffer.size(), STR_C(" Pressure: %.2f kPa (train pipe: %.2f kPa)"), physics->brakes.cylinderPressure * 100, - physics->brakePipe.pressure * 100 ); + physics->brakePipe.Pressure() * 100 ); expandedtext = m_buffer.data(); } if( readout.ed_percent ) { @@ -849,11 +849,11 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.converter.IsAllowed() ? 'x' : '.', physics.converter.IsOverloaded() ? '!' : '.', - physics.air.compressor.running ? 'C' : - false == physics.air.compressor.allowLocal ? '-' : - physics.air.compressor.allow || (physics.air.compressor.start == start_t::automatic && physics.air.compressor.speed > 0.0) ? 'c' : + physics.air.compressor.IsRunning() ? 'C' : + false == physics.air.compressor.LocalSwitchOn() ? '-' : + physics.air.compressor.IsAllowed() || (physics.air.compressor.config.start == start_t::automatic && physics.air.compressor.config.speed > 0.0) ? 'c' : '.', - physics.air.compressor.governorLock ? '!' : '.', + physics.air.compressor.IsGovernorLocked() ? '!' : '.', physics.lineContactors.IsForcedOpen() ? '-' : physics.protection.PressureSwitchTripped() ? '!' : physics.lineContactors.IsClosed() ? '+' : @@ -936,13 +936,13 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.brakes.independentCylinderPressure, physics.brakes.distributor->GetBrakeStatus(), // pipes - physics.brakePipe.pressure, + physics.brakePipe.Pressure(), physics.brakes.handleCapPosition, - physics.mainPipe.pressure, + physics.mainPipe.Pressure(), physics.brakes.controlReservoirPressure, // tanks physics.brakes.distributor->GetBRP(), - physics.air.mainReservoirPressure, + physics.air.MainReservoirPressure(), physics.brakes.distributor->GetCRP() ); textline = m_buffer.data(); diff --git a/input/messaging.cpp b/input/messaging.cpp index e58483baa..8e4b6829c 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -284,10 +284,10 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) r.fPar[9] = Vehicle->physics->AccN; // przyspieszenie Y //na razie nie r.fPar[10] = Vehicle->physics->AccVert; // przyspieszenie Z r.fPar[11] = Vehicle->physics->DistCounter; // przejechana odległość w km - r.fPar[12] = Vehicle->physics->brakePipe.pressure; // ciśnienie w PG - r.fPar[13] = Vehicle->physics->mainPipe.pressure; // ciśnienie w PZ + r.fPar[12] = Vehicle->physics->brakePipe.Pressure(); // ciśnienie w PG + r.fPar[13] = Vehicle->physics->mainPipe.Pressure(); // ciśnienie w PZ r.fPar[14] = Vehicle->physics->brakes.cylinderPressure; // ciśnienie w CH - r.fPar[15] = Vehicle->physics->air.mainReservoirPressure; // ciśnienie w ZG + r.fPar[15] = Vehicle->physics->air.MainReservoirPressure(); // ciśnienie w ZG r.fPar[16] = Vehicle->physics->Itot; // Prąd całkowity r.iPar[17] = Vehicle->physics->MainCtrlPos; // Pozycja NJ r.iPar[18] = Vehicle->physics->ScndCtrlPos; // Pozycja NB @@ -296,7 +296,7 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) r.iPar[21] = Vehicle->physics->ScndCtrlActualPos; // Pozycja bocznikowania r.iPar[22] = Vehicle->physics->ResistorsFlag * 1 + Vehicle->physics->converter.IsRunning() * 2 - + Vehicle->physics->air.compressor.running * 4 + + Vehicle->physics->air.compressor.IsRunning() * 4 + Vehicle->physics->lineBreaker.IsClosed() * 8 #ifdef EU07_USEOLDDOORCODE + Vehicle->physics->DoorLeftOpened * 16 diff --git a/physics/components/airsupply.h b/physics/components/airsupply.h index d81fc3e29..6a034f776 100644 --- a/physics/components/airsupply.h +++ b/physics/components/airsupply.h @@ -8,10 +8,12 @@ http://mozilla.org/MPL/2.0/. */ // the supply of compressed air of a vehicle: the compressor and the main reservoir, held by physics::Vehicle as air; and -// the pipes along the train, held by it as brakePipe and mainPipe +// the pipes along the train, held by it as brakePipe and mainPipe. as the parts of the main circuit (maincircuit.h): the +// definition in `config`, the state behind queries and operations #pragma once +#include #include #include @@ -23,11 +25,23 @@ namespace physics { // a pipe along the train, coupled by the hoses between the vehicles: the brake pipe, the main reservoir pipe -struct TrainPipe +class TrainPipe { + public: std::shared_ptr reservoir; - double pressure = 0.0; - bool couplersPending{false}; // the pipe stepped, its exchange of air through the hoses is yet to come (UpdatePipeCouplers()) + + // the pressure in the pipe [bar], as it was last taken from its reservoir + double const &Pressure() const { return pressure; } + // the pressure taken from the reservoir of the pipe, after the flows of a step + void SetPressure(double const Pressure) { pressure = Pressure; } + + // the pipe stepped, its exchange of air through the hoses is yet to come (UpdatePipeCouplers()) + bool CouplersPending() const { return couplersPending; } + void SetCouplersPending(bool const State) { couplersPending = State; } + + private: + double pressure{0.0}; + bool couplersPending{false}; }; // where the compressor gets its power from (CompressorPower of the .fiz), in the order of the numbers it had before @@ -41,44 +55,272 @@ enum class CompressorSupply rearUnitConverter, // Coupler2: from the converter of the unit behind }; -// the compressor of the main reservoir -struct AirCompressor +// what the compressor needs to know in the step +struct CompressorInputs { - // the definition (the Brake section of the .fiz) - double minPressure = 0.0; // MinCP: it starts below this pressure of the main reservoir - double maxPressure = 0.0; // MaxCP: it stops above this pressure - double minPressureCabA = 0.0; // the pressures of each cab, where they differ (MinCP_B, MaxCP_B given) - double maxPressureCabA = 0.0; - double minPressureCabB = 0.0; // MinCP_B - double maxPressureCabB = 0.0; // MaxCP_B - bool cabDependent = false; // the pressures follow the occupied cab - double speed = 0.0; // CompressorSpeed: how fast it fills the main reservoir - CompressorSupply supply{CompressorSupply::converterManual}; // CompressorPower - double startDelay{0.0}; // CompressorStartDelay: how long it waits after getting its power before it can start, after the engine starts say [s] - bool tankValve{false}; // CompressorTankValve: the pressure over the top is let out of its tank at once - start_t start{start_t::manual}; // CompressorStart: whether it is started by hand, or another way - // the programmer of the compressors of a unit (the CompressorList section), indexed by the cl_* rows - std::array, 4> list{}; - int listPositions = 0; // Size: the positions of its switch - int listDefaultPosition = 1; // Default - bool listWraps = false; // Wrap - // the state - bool running = false; // it runs - bool allow = false; // it may start - bool allowLocal{true}; // the switch of the vehicle itself; most have none, so it allows - bool governorLock{false}; // the governor switched it off at the cut-out pressure + bool converterAllowed{false}; // the converter of the vehicle may run + bool mainCircuitPowered{false}; // the main circuit has its power + bool lowVoltage110v{false}; // the 110 V circuit has its power + bool coupledGovernorLock{false}; // a vehicle coupled permanently has its compressor stopped by the governor + bool switchingDelayPassed{false}; // the vehicle may switch something on again (LastSwitchingTime > CtrlDelay) + double engineRpmRatio{0.0}; // the revolutions of the engine against the most at its position, for a compressor it drives +}; + +// what the step of the compressor did, for the vehicle to follow it up +struct CompressorStep +{ + bool switched{false}; // it started or stopped + bool vented{false}; // the reservoir let air out over the top pressure +}; + +// the compressor of the main reservoir +class AirCompressor +{ + public: + struct Config + { + // the definition (the Brake section of the .fiz). where the pressures follow the occupied cab (cabDependent) the + // compressor sets minPressure and maxPressure to those of the cab in each step + double minPressure{0.0}; // MinCP: it starts below this pressure of the main reservoir + double maxPressure{0.0}; // MaxCP: it stops above this pressure + double minPressureCabA{0.0}; // the pressures of each cab, where they differ (MinCP_B, MaxCP_B given) + double maxPressureCabA{0.0}; + double minPressureCabB{0.0}; // MinCP_B + double maxPressureCabB{0.0}; // MaxCP_B + bool cabDependent{false}; // the pressures follow the occupied cab + double speed{0.0}; // CompressorSpeed: how fast it fills the main reservoir + CompressorSupply supply{CompressorSupply::converterManual}; // CompressorPower + double startDelay{0.0}; // CompressorStartDelay: how long it waits after getting its power before it can start, after the engine starts say [s] + bool tankValve{false}; // CompressorTankValve: the pressure over the top is let out of its tank at once + start_t start{start_t::manual}; // CompressorStart: whether it is started by hand, or another way + // the programmer of the compressors of a unit (the CompressorList section), indexed by the cl_* rows + std::array, 4> list{}; + int listPositions{0}; // Size: the positions of its switch + int listDefaultPosition{1}; // Default + bool listWraps{false}; // Wrap + }; + Config config; + + // a compressor of no output doesn't count + bool IsFitted() const { return config.speed != 0.0; } + bool IsRunning() const { return running; } + void Stop() { running = false; } + + // it may start, as its switch (or what drives it) has it + bool IsAllowed() const { return allow; } + void Allow(bool const State) { allow = State; } + // the switch of the vehicle itself; most have none, so it allows + bool LocalSwitchOn() const { return allowLocal; } + void SetLocalSwitch(bool const State) { allowLocal = State; } + // the governor switched it off at the cut-out pressure + bool IsGovernorLocked() const { return governorLock; } + + // the position of the switch of the programmer + int ListPosition() const { return listPosition; } + void SetListPosition(int const Position) { listPosition = std::min(std::max(Position, 0), config.listPositions); } + // the programmer at its default position, as the vehicle is placed + void ResetListPosition() + { + if (config.listPositions > 0) + { + listPosition = config.listDefaultPosition; + } + } + + // the pressures of the occupied cab, where they follow it + void SelectCab(int const Cab) + { + if (false == config.cabDependent) + { + return; + } + if (Cab > 0) + { + config.minPressure = config.minPressureCabA; + config.maxPressure = config.maxPressureCabA; + } + if (Cab < 0) + { + config.minPressure = config.minPressureCabB; + config.maxPressure = config.maxPressureCabB; + } + } + + // the fault the scenery can set (the damage events): its pressures moved out of reach, so it never starts; and back + void SetFault(bool const State) + { + constexpr double faultoffset{100000001}; + if (State) + { + if (config.minPressure > 0) + config.minPressure -= faultoffset; + if (config.maxPressure > 0) + config.maxPressure -= faultoffset; + } + else + { + if (config.minPressure < 0) + config.minPressure += faultoffset; + if (config.maxPressure < 0) + config.maxPressure += faultoffset; + } + } + + // the step of the compressor, which works the reservoir of the given volume of compressed air at the given pressure + CompressorStep Update(CompressorInputs const &Inputs, double &CompressedVolume, double const ReservoirPressure, double const dt) + { + CompressorStep step; + // assorted operational logic + auto const maxpressure{config.list[cl_MaxFactor][listPosition] * config.maxPressure}; + auto const minpressure{config.list[cl_MinFactor][listPosition] * config.minPressure}; + auto const speed{config.list[cl_SpeedFactor][listPosition] * config.speed}; + // checking the impact on the compressor allowance + if (auto const allowfactor{config.list[cl_Allow][listPosition]}; allowfactor > 0.5) + { + allow = allowfactor > 1.5; + } + switch (config.supply) + { + case CompressorSupply::converter: + allow = Inputs.converterAllowed; + break; + case CompressorSupply::engine: + // HACK: make sure compressor coupled with diesel engine is always ready for work + config.start = start_t::automatic; + break; + default: + break; + } + + // the main circuit, also for a compressor driven by the engine, otherwise the low voltage + auto const power{config.supply == CompressorSupply::mainCircuit || config.supply == CompressorSupply::engine ? Inputs.mainCircuitPowered : Inputs.lowVoltage110v}; + powerTime = power ? powerTime + dt : 0.0; + auto const ready{power && powerTime >= config.startDelay}; + // TBD: split CompressorAllow into separate enable/disable flags, inherit compressor from basic_device + auto const enable{allowLocal && (config.start == start_t::automatic || allow)}; + + auto const pressuretoolow{ReservoirPressure < minpressure}; + auto const pressuretoohigh{ReservoirPressure > maxpressure}; + + // TBD, TODO: break the lock with no low voltage power? + auto const governorlockpresent{maxpressure - minpressure > 0.0001}; + governorLock = governorlockpresent && false == pressuretoolow // unlock if pressure drops below minimal threshold + && (pressuretoohigh || governorLock); // lock if pressure goes above maximum threshold + // for these multi-unit engines compressors turn off whenever any of them was affected by the governor + // NOTE: this is crude implementation, limited only to adjacent vehicles + // TODO: re-implement when a more elegant/flexible system is in place + auto const locked{governorLock || Inputs.coupledGovernorLock}; + + auto const wasrunning{running}; + running = ready && enable && (false == locked || config.supply == CompressorSupply::engine) && (running || (enable && Inputs.switchingDelayPassed)); + step.switched = running != wasrunning; + + if (false == running) + { + return step; + } + + // working compressor adds air to the air reservoir + if (config.supply == CompressorSupply::engine) + { + // the compressor is coupled with the diesel engine, engine revolutions affect the output + CompressedVolume += speed * (2.0 * maxpressure - ReservoirPressure) / maxpressure * Inputs.engineRpmRatio * dt * (governorLock ? 0.0 : 1.0); // with the lock active air is vented out + } + else + { + // the compressor is a stand-alone device, working at steady pace + CompressedVolume += speed * (2.0 * maxpressure - ReservoirPressure) / maxpressure * dt; + } + + if (pressuretoohigh && (false == governorlockpresent || config.supply == CompressorSupply::engine)) + { + // vent some air out if there's no governor lock to stop the compressor from exceeding acceptable pressure level + step.vented = true; + auto ventedfraction{0.999}; // HACK: drop a tiny bit so the sound doesn't trigger repeatedly + if (false == governorlockpresent) + { + ventedfraction = 0.80; // arbitrary amount + } + else if (config.tankValve) + { + ventedfraction = minpressure / maxpressure; // drop to mincompressor level + } + CompressedVolume *= ventedfraction; + if (false == governorlockpresent || config.tankValve) + { + governorLock = false; + } + } + return step; + } + + private: + bool running{false}; + bool allow{false}; + bool allowLocal{true}; + bool governorLock{false}; double powerTime{0.0}; // how long it has had its power [s] - int listPosition = 0; // the position of the switch of the programmer + int listPosition{0}; }; // the supply of compressed air -struct AirSupply +class AirSupply { + public: + struct Config + { + double mainReservoirVolume{0.0}; // Vv: the volume of the main reservoir + double leakRate{0.01}; // AirLeakRate: the base rate of the air leaking from the components of the brakes (0.001 = 1 l/s) + }; + Config config; + AirCompressor compressor; - double mainReservoirVolume = 0.0; // Vv: the volume of the main reservoir - double mainReservoirPressure = 0.0; // the pressure in the main reservoir - double compressedVolume = 0.0; // the compressed air in the supply - double leakRate{0.01}; // AirLeakRate: the base rate of the air leaking from the components of the brakes (0.001 = 1 l/s) + + // the pressure in the main reservoir [bar], as the last step found it + double const &MainReservoirPressure() const { return mainReservoirPressure; } + // the pressure taken from the air in the reservoir; an empty one of no volume has none, and stops the compressor + void UpdatePressure() + { + if (config.mainReservoirVolume > 0) + { + mainReservoirPressure = compressedVolume / config.mainReservoirVolume; + } + else + { + mainReservoirPressure = 0; + compressor.Stop(); + } + } + + // the compressed air in the supply + double CompressedVolume() const { return compressedVolume; } + // air let into the reservoir, or out of it with a negative volume + void AddAir(double const Volume) { compressedVolume += Volume; } + // the reservoir filled with the given volume of compressed air, as the vehicle is placed + void Fill(double const Volume) { compressedVolume = Volume; } + // no air below nothing + void ClampEmpty() + { + if (compressedVolume < 0.0) + { + compressedVolume = 0.0; + } + } + + // the step of the reservoir and its compressor: the leaks, then the compressor, which fills it + CompressorStep Update(CompressorInputs const &Inputs, double const dt) + { + compressedVolume = std::max(0.0, compressedVolume - dt * config.leakRate * 0.1); // nieszczelności: 0.001=1l/s + mainReservoirPressure = compressedVolume / config.mainReservoirVolume; + return compressor.Update(Inputs, compressedVolume, mainReservoirPressure, dt); + } + + // for the tests: the pressure in the reservoir as given, whatever its air + void SetPressureForTest(double const Pressure) { mainReservoirPressure = Pressure; } + + private: + double mainReservoirPressure{0.0}; + double compressedVolume{0.0}; }; } // namespace physics diff --git a/physics/components/body.cpp b/physics/components/body.cpp index 2e3c533d4..aa1d84224 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -91,13 +91,13 @@ physics::Vehicle::Vehicle(double VelInitial, std::string const &TypeNameInit, st for (int k = 0; k < 17; ++k) cablights[k] = 0; - for (auto &compressorrow : air.compressor.list) + for (auto &compressorrow : air.compressor.config.list) for (int k = 1; k < 9; ++k) compressorrow[k] = 0; - air.compressor.list[0][0] = 0.0; - air.compressor.list[1][0] = 1.0; - air.compressor.list[2][0] = 1.0; - air.compressor.list[3][0] = 1.0; + air.compressor.config.list[0][0] = 0.0; + air.compressor.config.list[1][0] = 1.0; + air.compressor.config.list[2][0] = 1.0; + air.compressor.config.list[3][0] = 1.0; for (int b = -1; b <= MainBrakeMaxPos; ++b) { @@ -474,14 +474,8 @@ void physics::Vehicle::compute_movement_(double const Deltatime) MotorBlowersCheck(Deltatime); // uklady hamulcowe: ConverterCheck(Deltatime); - if (air.mainReservoirVolume > 0) - air.mainReservoirPressure = air.compressedVolume / air.mainReservoirVolume; - else - { - air.mainReservoirPressure = 0; - air.compressor.running = false; - } - if (air.mainReservoirVolume > 0.0) + air.UpdatePressure(); + if (air.config.mainReservoirVolume > 0.0) { // sprężarka musi mieć jakąś niezerową wydajność żeby rozważać jej załączenie i pracę CompressorCheck(Deltatime); @@ -840,7 +834,7 @@ void physics::Vehicle::ComputeTotalForce(double dt) double old_nrot = abs(nrot); nrot = v2n(); // przeliczenie prędkości liniowej na obrotową - if (true == TestFlag(brakes.method, bp_MHS) && brakePipe.pressure < 3.0 // ustawione na sztywno na 3 bar + if (true == TestFlag(brakes.method, bp_MHS) && brakePipe.Pressure() < 3.0 // ustawione na sztywno na 3 bar && Vel > 45 && true == TestFlag(brakes.delaySetting, bdelay_M)) { // doliczenie hamowania hamulcem szynowym diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index ed68b611c..4ec0ad598 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -57,7 +57,7 @@ bool physics::Vehicle::ChangeCab(int direction) if (brakes.handlePositions > 0 && (brakes.kind == TBrakeSystem::Pneumatic || brakes.kind == TBrakeSystem::ElectroPneumatic)) { BrakeLevelSet(brakes.driverValve->GetPos(bh_NP)); - brakes.pipeLimiterPressure = brakePipe.pressure; + brakes.pipeLimiterPressure = brakePipe.Pressure(); ActFlowSpeed = 0; } else @@ -76,14 +76,14 @@ int physics::Vehicle::SoundingHorns(int const Signal) const { return lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable(); } - if (air.mainReservoirVolume > 0.0) + if (air.config.mainReservoirVolume > 0.0) { - return air.mainReservoirPressure >= HornMinPressure; + return air.MainReservoirPressure() >= HornMinPressure; } // a vehicle without a main reservoir of its own takes the air from the main pipe, a vehicle without either // (a road vehicle, say) has no air to check auto const mainpipe{(Couplers[VehicleEnd::front].AllowedFlag | Couplers[VehicleEnd::rear].AllowedFlag).HasAny(Coupling::mainHose)}; - return false == mainpipe || mainPipe.pressure >= HornMinPressure; + return false == mainpipe || mainPipe.Pressure() >= HornMinPressure; }}; auto horns{0}; if (supplied(HornSupply)) diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 80b8c153d..44c87d814 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -389,7 +389,7 @@ bool physics::Vehicle::RunAuxiliariesCommand(VehicleCommand const Command, doubl } else if (Command == VehicleCommand::compressorPreset) { - air.compressor.listPosition = safe_clamp(static_cast(CValue1), 0, air.compressor.listPositions); + air.compressor.SetListPosition(static_cast(CValue1)); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index 4016f25a9..df91588b2 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -894,7 +894,7 @@ bool physics::Vehicle::MotorConnectorsCheck() // hunter-111211: wylacznik cisnieniowy // (on some vehicles it watches the brake pipe alone) - protection.UpdatePressureSwitch(brakes.cylinderPressure, brakePipe.pressure); + protection.UpdatePressureSwitch(brakes.cylinderPressure, brakePipe.Pressure()); if (true == protection.PressureSwitchTripped()) { @@ -1253,7 +1253,7 @@ void physics::Vehicle::CheckSpeedCtrl(double dt) { SpeedCtrlUnit.Standby = false; } - if (!SpeedCtrlUnit.BrakeIntervention && (brakes.distributor->GetEDBCP() > 0.4 || brakePipe.pressure < brakes.pipeHighPressure - 0.2)) + if (!SpeedCtrlUnit.BrakeIntervention && (brakes.distributor->GetEDBCP() > 0.4 || brakePipe.Pressure() < brakes.pipeHighPressure - 0.2)) SpeedCtrlUnit.Standby = true; if (EIMCtrlType >= 3 && UniCtrlList[MainCtrlPos].SpeedUp <= 0) { diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index d11d02638..5ff81e000 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -385,7 +385,7 @@ public: { ++vehicle.MainCtrlPos; } - vehicle.air.compressor.allow = vehicle.MainCtrlPowerPos() > 0; + vehicle.air.compressor.Allow(vehicle.MainCtrlPowerPos() > 0); return true; } bool DecreaseMainController(physics::Vehicle &vehicle, int const speed) const override diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index 09b9b3290..49c64167a 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -49,7 +49,7 @@ physics::PantographAirSupply physics::Vehicle::PantographAirSupplyNow() const // tylko jeśli pantografujący supply.collectors = EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0; supply.multipleUnit = TrainType == train_type::emu; - supply.mainReservoirPressure = mainPipe.pressure; + supply.mainReservoirPressure = mainPipe.Pressure(); supply.controlReservoirPressure = brakes.controlReservoirPressure; supply.maxPressure = EnginePowerSource.CollectorParameters.MaxPress; supply.minPressure = EnginePowerSource.CollectorParameters.MinPress; diff --git a/physics/components/fizparser.cpp b/physics/components/fizparser.cpp index ca86e3de5..debbeb149 100644 --- a/physics/components/fizparser.cpp +++ b/physics/components/fizparser.cpp @@ -546,7 +546,7 @@ bool physics::Vehicle::readCompressorList(std::string const &Input) return false; } // NOTE: content of slot [x][0] is hardcoded elsewhere - parser >> air.compressor.list[0][idx + 1] >> air.compressor.list[1][idx + 1] >> air.compressor.list[2][idx + 1] >> air.compressor.list[3][idx + 1]; + parser >> air.compressor.config.list[0][idx + 1] >> air.compressor.config.list[1][idx + 1] >> air.compressor.config.list[2][idx + 1] >> air.compressor.config.list[3][idx + 1]; return true; } diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index a4d346bfc..d86a04e80 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -291,16 +291,16 @@ void physics::Vehicle::LoadFIZ_Brake(std::string const &line) extract_value(brakes.pipeLowPressure, "LoPP", line, ""); brakes.pipePressureRange = brakes.pipeHighPressure - brakes.pipeLowPressure; - extract_value(air.mainReservoirVolume, "Vv", line, ""); + extract_value(air.config.mainReservoirVolume, "Vv", line, ""); /* if( VeselVolume == 0.0 ) { VeselVolume = 0.01; } */ - extract_value(air.compressor.minPressure, "MinCP", line, ""); - extract_value(air.compressor.maxPressure, "MaxCP", line, ""); - extract_value(air.compressor.minPressureCabB, "MinCP_B", line, ""); - extract_value(air.compressor.maxPressureCabB, "MaxCP_B", line, ""); - extract_value(air.compressor.tankValve, "CompressorTankValve", line, ""); - extract_value(air.compressor.speed, "CompressorSpeed", line, ""); + extract_value(air.compressor.config.minPressure, "MinCP", line, ""); + extract_value(air.compressor.config.maxPressure, "MaxCP", line, ""); + extract_value(air.compressor.config.minPressureCabB, "MinCP_B", line, ""); + extract_value(air.compressor.config.maxPressureCabB, "MaxCP_B", line, ""); + extract_value(air.compressor.config.tankValve, "CompressorTankValve", line, ""); + extract_value(air.compressor.config.speed, "CompressorSpeed", line, ""); extract_value(brakes.emergencyValve.offPressure, "MinEVP", line, ""); extract_value(brakes.emergencyValve.onPressure, "MaxEVP", line, ""); extract_value(brakes.emergencyValve.area, "EVArea", line, ""); @@ -322,35 +322,35 @@ void physics::Vehicle::LoadFIZ_Brake(std::string const &line) {"Coupler2", rearUnitConverter} // włączana w silnikowym EZT z tyłu }; auto lookup = compressorpowers.find(extract_value("CompressorPower", line)); - air.compressor.supply = lookup != compressorpowers.end() ? lookup->second : converterManual; + air.compressor.config.supply = lookup != compressorpowers.end() ? lookup->second : converterManual; } - extract_value(air.compressor.startDelay, "CompressorStartDelay", line, ""); + extract_value(air.compressor.config.startDelay, "CompressorStartDelay", line, ""); - if (true == extract_value(air.leakRate, "AirLeakRate", line, "")) + if (true == extract_value(air.config.leakRate, "AirLeakRate", line, "")) { // the parameter is provided in form of a multiplier, where 1.0 means the default rate of 0.01 - air.leakRate *= 0.01; + air.config.leakRate *= 0.01; } extract_value(ReleaserEnabledOnlyAtNoPowerPos, "ReleaserPowerPosLock", line, EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric ? "yes" : "no"); - if (air.compressor.minPressureCabB > 0.0) + if (air.compressor.config.minPressureCabB > 0.0) { - air.compressor.minPressureCabA = air.compressor.minPressure; - air.compressor.cabDependent = true; + air.compressor.config.minPressureCabA = air.compressor.config.minPressure; + air.compressor.config.cabDependent = true; } else { - air.compressor.minPressureCabB = air.compressor.minPressure; + air.compressor.config.minPressureCabB = air.compressor.config.minPressure; } - if (air.compressor.maxPressureCabB > 0.0) + if (air.compressor.config.maxPressureCabB > 0.0) { - air.compressor.maxPressureCabA = air.compressor.maxPressure; - air.compressor.cabDependent = true; + air.compressor.config.maxPressureCabA = air.compressor.config.maxPressure; + air.compressor.config.cabDependent = true; } else { - air.compressor.maxPressureCabB = air.compressor.maxPressure; + air.compressor.config.maxPressureCabB = air.compressor.config.maxPressure; } } @@ -933,7 +933,7 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) // compressor { auto lookup = starts.find(extract_value("CompressorStart", line)); - air.compressor.start = lookup != starts.end() ? lookup->second : manual; + air.compressor.config.start = lookup != starts.end() ? lookup->second : manual; } // pantograph compressor { @@ -1669,9 +1669,9 @@ void physics::Vehicle::LoadFIZ_LightsList(std::string const &Input) void physics::Vehicle::LoadFIZ_CompressorList(std::string const &Input) { - extract_value(air.compressor.listPositions, "Size", Input, ""); - extract_value(air.compressor.listWraps, "Wrap", Input, ""); - extract_value(air.compressor.listDefaultPosition, "Default", Input, ""); + extract_value(air.compressor.config.listPositions, "Size", Input, ""); + extract_value(air.compressor.config.listWraps, "Wrap", Input, ""); + extract_value(air.compressor.config.listDefaultPosition, "Default", Input, ""); } void physics::Vehicle::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const &Prefix, std::string const &Line) diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 4156ec35e..3fc4ba6a0 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -189,7 +189,7 @@ double physics::Vehicle::RealPipeRatio(void) const double rpp; if (brakes.pipePressureRange > 0) - rpp = (brakes.controlReservoirPressure - brakePipe.pressure) / brakes.pipePressureRange; + rpp = (brakes.controlReservoirPressure - brakePipe.Pressure()) / brakes.pipePressureRange; else rpp = 0; return rpp; @@ -206,10 +206,10 @@ double physics::Vehicle::PipeRatio(void) const if (brakes.pipePressureRange > 0) if (false) // SPKS!! no to jak nie wchodzimy to po co branch? { - if (3.0 * brakePipe.pressure > brakes.pipeHighPressure + brakes.pipeLowPressure + brakes.pipeLowPressure) - pr = (brakes.pipeHighPressure - std::min(brakes.pipeHighPressure, brakePipe.pressure)) / (brakes.pipePressureRange * 4.0 / 3.0); + if (3.0 * brakePipe.Pressure() > brakes.pipeHighPressure + brakes.pipeLowPressure + brakes.pipeLowPressure) + pr = (brakes.pipeHighPressure - std::min(brakes.pipeHighPressure, brakePipe.Pressure())) / (brakes.pipePressureRange * 4.0 / 3.0); else - pr = (brakes.pipeHighPressure - 1.0 / 3.0 * brakes.pipePressureRange - std::max(brakes.pipeLowPressure, brakePipe.pressure)) / (brakes.pipePressureRange * 2.0 / 3.0); + pr = (brakes.pipeHighPressure - 1.0 / 3.0 * brakes.pipePressureRange - std::max(brakes.pipeLowPressure, brakePipe.Pressure())) / (brakes.pipePressureRange * 2.0 / 3.0); // if (not TestFlag(BrakeStatus, b_Ractive)) // and(BrakeMethod and 1 = 0) and TestFlag(BrakeDelays, bdelay_R) and (Power < 1) and // (BrakeCtrlPos < 1) then pr : = std::min(0.5, pr); @@ -217,7 +217,7 @@ double physics::Vehicle::PipeRatio(void) const // then pr : = pr * 1.333; // dziwny rapid wywalamy } else - pr = (brakes.pipeHighPressure - std::max(brakes.pipeLowPressure, std::min(brakes.pipeHighPressure, brakePipe.pressure))) / brakes.pipePressureRange; + pr = (brakes.pipeHighPressure - std::max(brakes.pipeLowPressure, std::min(brakes.pipeHighPressure, brakePipe.Pressure()))) / brakes.pipePressureRange; else pr = 0; return pr; @@ -308,17 +308,17 @@ bool physics::Vehicle::AntiSlippingButton(void) bool physics::Vehicle::CompressorSwitch(bool State, range_t const Notify) { - if (air.compressor.start != start_t::manual) + if (air.compressor.config.start != start_t::manual) { // only pay attention if the compressor can be controlled manually return false; } - auto const initialstate{air.compressor.allow}; + auto const initialstate{air.compressor.IsAllowed()}; - if (air.mainReservoirVolume > 0.0 && air.compressor.speed > 0.0) + if (air.config.mainReservoirVolume > 0.0 && air.compressor.config.speed > 0.0) { - air.compressor.allow = State; + air.compressor.Allow(State); } if (Notify != range_t::local) @@ -326,22 +326,22 @@ bool physics::Vehicle::CompressorSwitch(bool State, range_t const Notify) SendCtrlToNext(VehicleCommand::compressorSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return air.compressor.allow != initialstate; + return air.compressor.IsAllowed() != initialstate; } bool physics::Vehicle::ChangeCompressorPreset(int const State, range_t const Notify) { - auto const initialstate{air.compressor.listPosition}; + auto const initialstate{air.compressor.ListPosition()}; - air.compressor.listPosition = safe_clamp(State, 0, air.compressor.listPositions); + air.compressor.SetListPosition(State); if (Notify != range_t::local) { SendCtrlToNext(VehicleCommand::compressorPreset, State, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return air.compressor.listPosition != initialstate; + return air.compressor.ListPosition() != initialstate; } // ************************************************************************************************* @@ -360,7 +360,7 @@ bool physics::Vehicle::IncBrakeLevelOld(void) // youBy: EP po nowemu IBLO = true; if (brakes.actualPressure.PipePressureVal < 0 && brakes.pressureTable[brakes.handlePosition - 1].PipePressureVal > 0) - brakes.pipeLimiterPressure = brakePipe.pressure; + brakes.pipeLimiterPressure = brakePipe.Pressure(); } else { @@ -727,7 +727,7 @@ void physics::Vehicle::UpdateBrakePressure(double dt) brakes.independentValveFlow = 0; brakes.brakeFlow = 0; - brakes.distributor->ForceLeak(dt * air.leakRate * 0.25); // fake air leaks from brake system reservoirs + brakes.distributor->ForceLeak(dt * air.config.leakRate * 0.25); // fake air leaks from brake system reservoirs auto const brakepress{brakes.cylinderPressure}; brakes.cylinderPressure = brakes.distributor->GetBCP(); @@ -747,143 +747,50 @@ void physics::Vehicle::UpdateBrakePressure(double dt) // ************************************************************************************************* void physics::Vehicle::CompressorCheck(double dt) { - - if (air.compressor.speed == 0.0) + auto &compressor{air.compressor}; + if (false == compressor.IsFitted()) { - air.compressor.allow = false; + compressor.Allow(false); return; } - - if (air.compressor.cabDependent) - { - if (CabActive > 0) - { - air.compressor.minPressure = air.compressor.minPressureCabA; - air.compressor.maxPressure = air.compressor.maxPressureCabA; - } - if (CabActive < 0) - { - air.compressor.minPressure = air.compressor.minPressureCabB; - air.compressor.maxPressure = air.compressor.maxPressureCabB; - } - } + compressor.SelectCab(CabActive); // EmergencyValve - brakes.emergencyValve.open = air.mainReservoirPressure > (brakes.emergencyValve.open ? brakes.emergencyValve.offPressure : brakes.emergencyValve.onPressure); + brakes.emergencyValve.open = air.MainReservoirPressure() > (brakes.emergencyValve.open ? brakes.emergencyValve.offPressure : brakes.emergencyValve.onPressure); if (brakes.emergencyValve.open) { - auto dV = static_cast(PF(0, air.mainReservoirPressure, brakes.emergencyValve.area) * dt); - air.compressedVolume -= dV; + auto dV = static_cast(PF(0, air.MainReservoirPressure(), brakes.emergencyValve.area) * dt); + air.AddAir(-dV); } - air.compressedVolume = std::max(0.0, air.compressedVolume - dt * air.leakRate * 0.1); // nieszczelności: 0.001=1l/s - - air.mainReservoirPressure = air.compressedVolume / air.mainReservoirVolume; - - // assorted operational logic - auto const MaxCompressorF{air.compressor.list[TCompressorList::cl_MaxFactor][air.compressor.listPosition] * air.compressor.maxPressure}; - auto const MinCompressorF{air.compressor.list[TCompressorList::cl_MinFactor][air.compressor.listPosition] * air.compressor.minPressure}; - auto const CompressorSpeedF{air.compressor.list[TCompressorList::cl_SpeedFactor][air.compressor.listPosition] * air.compressor.speed}; - // checking the impact on the compressor allowance - if (auto const AllowFactor{air.compressor.list[TCompressorList::cl_Allow][air.compressor.listPosition]}; AllowFactor > 0.5) - { - air.compressor.allow = AllowFactor > 1.5; - } - - switch (air.compressor.supply) - { - case CompressorSupply::converter: - { - air.compressor.allow = converter.IsAllowed(); - break; - } - case CompressorSupply::engine: - { - // HACK: make sure compressor coupled with diesel engine is always ready for work - air.compressor.start = start_t::automatic; - break; - } - default: - { - break; - } - } - - // the main circuit, also for a compressor driven by the engine, otherwise the low voltage - auto const compressorpower{air.compressor.supply == CompressorSupply::mainCircuit || air.compressor.supply == CompressorSupply::engine ? MainCircuitPowered() : lowVoltage.Is110vAvailable()}; - air.compressor.powerTime = compressorpower ? air.compressor.powerTime + dt : 0.0; - auto const compressorready{compressorpower && air.compressor.powerTime >= air.compressor.startDelay}; - // TBD: split CompressorAllow into separate enable/disable flags, inherit compressor from basic_device - auto const compressorenable{air.compressor.allowLocal && (air.compressor.start == start_t::automatic || air.compressor.allow)}; - auto const compressordisable{false == compressorenable}; - - auto const pressureistoolow{air.mainReservoirPressure < MinCompressorF}; - auto const pressureistoohigh{air.mainReservoirPressure > MaxCompressorF}; - - // TBD, TODO: break the lock with no low voltage power? - auto const governorlockispresent{MaxCompressorF - MinCompressorF > 0.0001}; - air.compressor.governorLock = governorlockispresent && false == pressureistoolow // unlock if pressure drops below minimal threshold - && (pressureistoohigh || air.compressor.governorLock); // lock if pressure goes above maximum threshold + CompressorInputs inputs; + inputs.converterAllowed = converter.IsAllowed(); + inputs.mainCircuitPowered = MainCircuitPowered(); + inputs.lowVoltage110v = lowVoltage.Is110vAvailable(); // for these multi-unit engines compressors turn off whenever any of them was affected by the governor // NOTE: this is crude implementation, limited only to adjacent vehicles - // TODO: re-implement when a more elegant/flexible system is in place - auto const coupledgovernorlock{ - (Couplers[VehicleEnd::rear].Connected != nullptr && true == Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::permanent) && Couplers[VehicleEnd::rear].Connected->air.compressor.governorLock) || - (Couplers[VehicleEnd::front].Connected != nullptr && true == Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::permanent) && Couplers[VehicleEnd::front].Connected->air.compressor.governorLock)}; - auto const governorlock{air.compressor.governorLock || coupledgovernorlock}; + auto const governorlocked = [this](VehicleEnd const End) { + auto const &coupler{Couplers[End]}; + return coupler.Connected != nullptr && coupler.CouplingFlag.HasAll(Coupling::permanent) && coupler.Connected->air.compressor.IsGovernorLocked(); + }; + inputs.coupledGovernorLock = governorlocked(VehicleEnd::rear) || governorlocked(VehicleEnd::front); + inputs.switchingDelayPassed = LastSwitchingTime > CtrlDelay; + inputs.engineRpmRatio = EngineRPMRatio(); - auto const compressorflag{air.compressor.running}; - air.compressor.running = - compressorready && false == compressordisable && (false == governorlock || air.compressor.supply == CompressorSupply::engine) && (air.compressor.running || (compressorenable && LastSwitchingTime > CtrlDelay)); - - if (air.compressor.running && air.compressor.running != compressorflag) + auto const step{air.Update(inputs, dt)}; + if (step.switched) { - // jeśli została załączona to trzeba ograniczyć ponowne włączenie - LastSwitchingTime = 0; + if (compressor.IsRunning()) + { + // jeśli została załączona to trzeba ograniczyć ponowne włączenie + LastSwitchingTime = 0; + } + Timer::subsystem.switching.note(compressor.IsRunning() ? Timer::switching_counter::compressor_on : Timer::switching_counter::compressor_off, this, &TypeName, &Name); } - if (air.compressor.running != compressorflag) + if (step.vented) { - Timer::subsystem.switching.note(air.compressor.running ? Timer::switching_counter::compressor_on : Timer::switching_counter::compressor_off, this, &TypeName, &Name); - } - - if (false == air.compressor.running) - { - return; - } - - // working compressor adds air to the air reservoir - if (air.compressor.supply == CompressorSupply::engine) - { - // the compressor is coupled with the diesel engine, engine revolutions affect the output - air.compressedVolume += - CompressorSpeedF * (2.0 * MaxCompressorF - air.mainReservoirPressure) / MaxCompressorF * EngineRPMRatio() * dt * (air.compressor.governorLock ? 0.0 : 1.0); // with the lock active air is vented out - } - else - { - // the compressor is a stand-alone device, working at steady pace - air.compressedVolume += CompressorSpeedF * (2.0 * MaxCompressorF - air.mainReservoirPressure) / MaxCompressorF * dt; - } - - if (pressureistoohigh && (false == governorlockispresent || air.compressor.supply == CompressorSupply::engine)) - { - // vent some air out if there's no governor lock to stop the compressor from exceeding acceptable pressure level SetFlag(SoundFlag, sound::relay | sound::loud); - auto ventedfraction{0.999}; // HACK: drop a tiny bit so the sound doesn't trigger repeatedly - if (false == governorlockispresent) - { - ventedfraction = 0.80; // arbitrary amount - } - else if (air.compressor.tankValve) - { - ventedfraction = MinCompressorF / MaxCompressorF; // drop to mincompressor level - } - air.compressedVolume *= ventedfraction; - if (false == governorlockispresent || air.compressor.tankValve) - { - air.compressor.governorLock = false; - } } - // a compressor not driven by the engine doesn't draw power (some 5 A) from the high- or low voltage circuit yet } @@ -893,9 +800,9 @@ void physics::Vehicle::CompressorCheck(double dt) // ************************************************************************************************* void physics::Vehicle::UpdatePipePressure(double dt) { - if (brakePipe.pressure > 1.0) + if (brakePipe.Pressure() > 1.0) { - brakePipe.reservoir->Flow(-brakePipe.pressure*air.leakRate * dt); + brakePipe.reservoir->Flow(-brakePipe.Pressure()*air.config.leakRate * dt); brakePipe.reservoir->Act(); } @@ -904,7 +811,7 @@ void physics::Vehicle::UpdatePipePressure(double dt) double temp; // int b; - brakePipe.pressure = brakePipe.reservoir->P(); + brakePipe.SetPressure(brakePipe.reservoir->P()); // PPP:=PipePress; brakes.driverValveFlow = 0; @@ -920,7 +827,7 @@ void physics::Vehicle::UpdatePipePressure(double dt) // 0.2*Spg brakePipe.reservoir->Flow(-brakes.driverValveFlow); - brakePipe.reservoir->Flow(-brakePipe.pressure * 0.001 * dt); + brakePipe.reservoir->Flow(-brakePipe.Pressure() * 0.001 * dt); // if Heating then // Pipe.Flow(PF(PipePress, 0, d2A(7)) * dt); // if ConverterFlag then @@ -944,14 +851,14 @@ void physics::Vehicle::UpdatePipePressure(double dt) } brakePipe.reservoir->Act(); - brakePipe.pressure = brakePipe.reservoir->P(); + brakePipe.SetPressure(brakePipe.reservoir->P()); if ((brakes.distributor->GetBrakeStatus() & b_dmg) == b_dmg) // jesli hamulec wyłączony temp = 0.0; // odetnij else temp = 1.0; // połącz - brakePipe.reservoir->Flow(temp * brakes.distributor->GetPF(temp * brakePipe.pressure, dt, Vel)); + brakePipe.reservoir->Flow(temp * brakes.distributor->GetPF(temp * brakePipe.Pressure(), dt, Vel)); // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() - brakePipe.couplersPending = true; + brakePipe.SetCouplersPending(true); if (brakes.antiSlipType == 128) brakes.distributor->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); @@ -960,19 +867,18 @@ void physics::Vehicle::UpdatePipePressure(double dt) // yB: jednokrokowe liczenie tego wszystkiego brakePipe.reservoir->Act(); - brakePipe.pressure = brakePipe.reservoir->P(); + brakePipe.SetPressure(brakePipe.reservoir->P()); brakes.driverValveFlow = brakes.driverValveFlow / (100.0 * dt); // normalizacja po czasie do syczenia; - if (brakePipe.pressure < -1.0) + if (brakePipe.Pressure() < -1.0) { - brakePipe.pressure = -1.0; + brakePipe.SetPressure(-1.0); brakePipe.reservoir->CreatePress(-1.0); brakePipe.reservoir->Act(); } - if (air.compressedVolume < 0.0) - air.compressedVolume = 0.0; + air.ClampEmpty(); } // the flow of the local brake valve, by the handle, the TRAXX's timed one, the integrated controller or the parking @@ -990,7 +896,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) { lbpa = std::max(lbpa, brakes.holding.deceleration); } - brakes.independentValveFlow = brakes.independentValve->GetPF(PulleeMode ? 0.0 : std::max(lbpa, brakes.independentPositionEim), brakes.distributor->GetBCP(), mainPipe.pressure, dt, 0); + brakes.independentValveFlow = brakes.independentValve->GetPF(PulleeMode ? 0.0 : std::max(lbpa, brakes.independentPositionEim), brakes.distributor->GetBCP(), mainPipe.Pressure(), dt, 0); } else { @@ -1011,7 +917,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) { lbpa = 0.0; } - brakes.independentValveFlow = brakes.independentValve->GetPF(PulleeMode ? 0.0 : std::max(lbpa, brakes.independentPositionEim), brakes.distributor->GetBCP(), mainPipe.pressure, dt, 0); + brakes.independentValveFlow = brakes.independentValve->GetPF(PulleeMode ? 0.0 : std::max(lbpa, brakes.independentPositionEim), brakes.distributor->GetBCP(), mainPipe.Pressure(), dt, 0); } } @@ -1031,23 +937,23 @@ void physics::Vehicle::UpdateMainValve(double dt) if (brakes.operatingMode < bom_EP || brakes.driverValve->GetPos(bh_EB) - 0.5 < brakes.handlePositionReal || (brakes.driverValveType != TBrakeHandle::MHZ_EN57 && brakes.driverValveType != TBrakeHandle::MHZ_K8P)) { - brakes.driverValveFlow = brakes.driverValve->GetPF(MainValveHandlePosition(), brakePipe.pressure, temp, dt, brakes.equivalentPipePressure); + brakes.driverValveFlow = brakes.driverValve->GetPF(MainValveHandlePosition(), brakePipe.Pressure(), temp, dt, brakes.equivalentPipePressure); } else { - brakes.driverValveFlow = brakes.driverValve->GetPF(0, brakePipe.pressure, temp, dt, brakes.equivalentPipePressure); + brakes.driverValveFlow = brakes.driverValve->GetPF(0, brakePipe.Pressure(), temp, dt, brakes.equivalentPipePressure); } } else if (brakes.handlePosition == brakes.driverValve->GetPos(bh_EB)) { - brakes.driverValveFlow = brakes.driverValve->GetPF(brakes.handlePositionReal, brakePipe.pressure, temp, dt, brakes.equivalentPipePressure); + brakes.driverValveFlow = brakes.driverValve->GetPF(brakes.handlePositionReal, brakePipe.Pressure(), temp, dt, brakes.equivalentPipePressure); } if (brakes.driverValveFlow < 0) // && (PipePressureVal > 0.01) //50 { - if (air.mainReservoirPressure > mainPipe.pressure) + if (air.MainReservoirPressure() > mainPipe.Pressure()) { - air.compressedVolume = air.compressedVolume + brakes.driverValveFlow / 1500.0; + air.AddAir(brakes.driverValveFlow / 1500.0); mainPipe.reservoir->Flow(brakes.driverValveFlow / 3.0); } else @@ -1058,16 +964,16 @@ void physics::Vehicle::UpdateMainValve(double dt) // the pressure the driver's handle is fed from: the main pipe's, or the brake pipe's own with the pipe locked double physics::Vehicle::MainValveSupply() { - brakes.pipeLock.locked = brakePipe.pressure < (brakes.pipeLock.locked ? brakes.pipeLock.offPressure : brakes.pipeLock.onPressure); + brakes.pipeLock.locked = brakePipe.Pressure() < (brakes.pipeLock.locked ? brakes.pipeLock.offPressure : brakes.pipeLock.onPressure); bool lock_new = (brakes.pipeLock.locked && !brakes.pipeLock.unlockPressed && brakes.handlePositionReal > brakes.pipeLock.unlockHandlePosition) || (brakes.emergencyCutsOffDriverValve && brakes.emergencyValve.flow > 0); // new simple codition based on .fiz bool lock_old = brakes.driverValveType == TBrakeHandle::FV4a // old complex condition based on assumptions - && brakePipe.pressure < 2.75 && (brakes.distributor->GetStatus() & b_rls) == 0 && brakes.subsystem == TBrakeSubSystem::ss_LSt && TrainType != train_type::emu && !brakes.pipeLock.unlockPressed; + && brakePipe.Pressure() < 2.75 && (brakes.distributor->GetStatus() & b_rls) == 0 && brakes.subsystem == TBrakeSubSystem::ss_LSt && TrainType != train_type::emu && !brakes.pipeLock.unlockPressed; if (lock_old || lock_new) { - return brakePipe.pressure + 0.00001; + return brakePipe.Pressure() + 0.00001; } - return mainPipe.pressure; + return mainPipe.Pressure(); } // the position the driver's handle works at: its own, or the one the speed control's brake intervention sets @@ -1101,7 +1007,7 @@ void physics::Vehicle::UpdateEmergencyValve(double dt) (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)}; if (brakes.alarmChain || (ownemergency && false == PulleeMode)) { - brakes.emergencyValve.flow = PF(0, brakePipe.pressure, 0.15) * dt; + brakes.emergencyValve.flow = PF(0, brakePipe.Pressure(), 0.15) * dt; } brakes.driverValveFlow += brakes.emergencyValve.flow; } @@ -1246,9 +1152,9 @@ void physics::Vehicle::UpdateEPBrake() // ************************************************************************************************* void physics::Vehicle::UpdateScndPipePressure(double dt) { - if (mainPipe.pressure > 1.0) + if (mainPipe.Pressure() > 1.0) { - mainPipe.reservoir->Flow(-mainPipe.pressure*air.leakRate * dt); + mainPipe.reservoir->Flow(-mainPipe.Pressure()*air.config.leakRate * dt); mainPipe.reservoir->Act(); } @@ -1256,22 +1162,22 @@ void physics::Vehicle::UpdateScndPipePressure(double dt) UpdateSpringBrake(dt); - mainPipe.reservoir->Flow(brakes.distributor->GetHPFlow(mainPipe.pressure, dt)); + mainPipe.reservoir->Flow(brakes.distributor->GetHPFlow(mainPipe.Pressure(), dt)); // NOTE: condition disabled to allow the air flow from the main hose to the main tank as well - if (/* ( ( Compressor > ScndPipePress ) && ( */ air.mainReservoirVolume > 0.0 /* ) ) || ( TrainType == train_type::emu ) || ( TrainType == train_type::dmu ) */) + if (/* ( ( Compressor > ScndPipePress ) && ( */ air.config.mainReservoirVolume > 0.0 /* ) ) || ( TrainType == train_type::emu ) || ( TrainType == train_type::dmu ) */) { - double const dV = PF(air.mainReservoirPressure, mainPipe.pressure, Spz) * dt; - air.compressedVolume += dV / 1000.0; + double const dV = PF(air.MainReservoirPressure(), mainPipe.Pressure(), Spz) * dt; + air.AddAir(dV / 1000.0); mainPipe.reservoir->Flow(-dV); } // the air the main reservoir hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() - mainPipe.couplersPending = true; + mainPipe.SetCouplersPending(true); mainPipe.reservoir->Act(); - mainPipe.pressure = mainPipe.reservoir->P(); + mainPipe.SetPressure(mainPipe.reservoir->P()); - if (mainPipe.pressure < -1) + if (mainPipe.Pressure() < -1) { - mainPipe.pressure = -1; + mainPipe.SetPressure(-1); mainPipe.reservoir->CreatePress(-1); mainPipe.reservoir->Act(); } @@ -1352,18 +1258,18 @@ double physics::Vehicle::GetDVc(double dt) if (Couplers[0].Connected != nullptr && Couplers[0].CouplingFlag.HasAll(Coupling::brakeHose)) { //*0.85 c = Couplers[0].Connected; // skrot //0.08 //e/D * L/D = e/D^2 * L - dv1 = 0.5 * dt * PF(brakePipe.pressure, neighbour_pipe_pressure(*c, c->brakePipe.pressure, *c->brakePipe.reservoir), brakes.pipeSection / (1.0 + 0.015 / brakes.pipeSection * Dim.L)); + dv1 = 0.5 * dt * PF(brakePipe.Pressure(), neighbour_pipe_pressure(*c, c->brakePipe.Pressure(), *c->brakePipe.reservoir), brakes.pipeSection / (1.0 + 0.015 / brakes.pipeSection * Dim.L)); c->brakePipe.reservoir->Flow(-dv1); - if (pipe_wakes(dv1, brakePipe.pressure, *c->brakePipe.reservoir)) + if (pipe_wakes(dv1, brakePipe.Pressure(), *c->brakePipe.reservoir)) c->switch_physics(true, wake_cause::mainpipe); } // sprzeg 2 if (Couplers[1].Connected != nullptr && Couplers[1].CouplingFlag.HasAll(Coupling::brakeHose)) { c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(brakePipe.pressure, neighbour_pipe_pressure(*c, c->brakePipe.pressure, *c->brakePipe.reservoir), brakes.pipeSection / (1.0 + 0.015 / brakes.pipeSection * Dim.L)); + dv2 = 0.5 * dt * PF(brakePipe.Pressure(), neighbour_pipe_pressure(*c, c->brakePipe.Pressure(), *c->brakePipe.reservoir), brakes.pipeSection / (1.0 + 0.015 / brakes.pipeSection * Dim.L)); c->brakePipe.reservoir->Flow(-dv2); - if (pipe_wakes(dv2, brakePipe.pressure, *c->brakePipe.reservoir)) + if (pipe_wakes(dv2, brakePipe.Pressure(), *c->brakePipe.reservoir)) c->switch_physics(true, wake_cause::mainpipe); } // if ((Couplers[1].Connected != NULL) && (Couplers[0].Connected != NULL)) @@ -1395,23 +1301,23 @@ double physics::Vehicle::GetScndDVc(double dt) if (Couplers[0].Connected != nullptr && Couplers[0].CouplingFlag.HasAll(Coupling::mainHose)) { c = Couplers[0].Connected; // skrot - dv1 = 0.5 * dt * PF(mainPipe.pressure, neighbour_pipe_pressure(*c, c->mainPipe.pressure, *c->mainPipe.reservoir), Spz * 0.75); + dv1 = 0.5 * dt * PF(mainPipe.Pressure(), neighbour_pipe_pressure(*c, c->mainPipe.Pressure(), *c->mainPipe.reservoir), Spz * 0.75); c->mainPipe.reservoir->Flow(-dv1); - if (pipe_wakes(dv1, mainPipe.pressure, *c->mainPipe.reservoir)) + if (pipe_wakes(dv1, mainPipe.Pressure(), *c->mainPipe.reservoir)) c->switch_physics(true, wake_cause::scndpipe); } // sprzeg 2 if (Couplers[1].Connected != nullptr && Couplers[1].CouplingFlag.HasAll(Coupling::mainHose)) { c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(mainPipe.pressure, neighbour_pipe_pressure(*c, c->mainPipe.pressure, *c->mainPipe.reservoir), Spz * 0.75); + dv2 = 0.5 * dt * PF(mainPipe.Pressure(), neighbour_pipe_pressure(*c, c->mainPipe.Pressure(), *c->mainPipe.reservoir), Spz * 0.75); c->mainPipe.reservoir->Flow(-dv2); - if (pipe_wakes(dv2, mainPipe.pressure, *c->mainPipe.reservoir)) + if (pipe_wakes(dv2, mainPipe.Pressure(), *c->mainPipe.reservoir)) c->switch_physics(true, wake_cause::scndpipe); } if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && Couplers[0].CouplingFlag.HasAll(Coupling::mainHose) && Couplers[1].CouplingFlag.HasAll(Coupling::mainHose)) { - double const dV = 0.00025 * dt * PF(Couplers[0].Connected->mainPipe.pressure, Couplers[1].Connected->mainPipe.pressure, Spz * 0.25); + double const dV = 0.00025 * dt * PF(Couplers[0].Connected->mainPipe.Pressure(), Couplers[1].Connected->mainPipe.Pressure(), Spz * 0.25); Couplers[0].Connected->mainPipe.reservoir->Flow(+dV); Couplers[1].Connected->mainPipe.reservoir->Flow(-dV); } @@ -1457,7 +1363,7 @@ int hose_substeps(physics::Vehicle const &Vehicle, train_pipe const &trainPipe, auto const &other{*hose.Connected}; auto const othercapacity{(other.*trainPipe.pipe).reservoir->GetCap()}; // the flow per bar of the difference, at small differences, where it's the largest - auto const pressure{std::max((Vehicle.*trainPipe.pipe).pressure, (other.*trainPipe.pipe).pressure)}; + auto const pressure{std::max((Vehicle.*trainPipe.pipe).Pressure(), (other.*trainPipe.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))); @@ -1477,7 +1383,7 @@ std::vector hose_trains(std::vector const &Vehi byaddress.reserve(Vehicles.size()); for (std::size_t index = 0; index < Vehicles.size(); ++index) { - if ((Vehicles[index]->*trainPipe.pipe).couplersPending) + if ((Vehicles[index]->*trainPipe.pipe).CouplersPending()) { byaddress.emplace_back(Vehicles[index], index); } @@ -1491,7 +1397,7 @@ std::vector hose_trains(std::vector const &Vehi std::vector stack; for (std::size_t first = 0; first < Vehicles.size(); ++first) { - if (false == (Vehicles[first]->*trainPipe.pipe).couplersPending || trains[first] != none) + if (false == (Vehicles[first]->*trainPipe.pipe).CouplersPending() || trains[first] != none) { continue; } @@ -1530,7 +1436,7 @@ void exchange_through_hoses(std::vector const &Vehicles, tra std::vector substeps; for (std::size_t index = 0; index < Vehicles.size(); ++index) { - if (false == (Vehicles[index]->*trainPipe.pipe).couplersPending) + if (false == (Vehicles[index]->*trainPipe.pipe).CouplersPending()) { continue; } @@ -1547,23 +1453,23 @@ void exchange_through_hoses(std::vector const &Vehicles, tra { for (std::size_t index = 0; index < Vehicles.size(); ++index) { - if (false == (Vehicles[index]->*trainPipe.pipe).couplersPending || trains[index] != train) + if (false == (Vehicles[index]->*trainPipe.pipe).CouplersPending() || trains[index] != train) { continue; } auto *vehicle{Vehicles[index]}; auto &pipe{*(vehicle->*trainPipe.pipe).reservoir}; pipe.Act(); // what the neighbours have sent in the meantime - (vehicle->*trainPipe.pipe).pressure = pipe.P(); + (vehicle->*trainPipe.pipe).SetPressure(pipe.P()); pipe.Flow((vehicle->*trainPipe.exchange)(substep)); pipe.Act(); - (vehicle->*trainPipe.pipe).pressure = pipe.P(); + (vehicle->*trainPipe.pipe).SetPressure(pipe.P()); } } } for (auto *vehicle : Vehicles) { - (vehicle->*trainPipe.pipe).couplersPending = false; + (vehicle->*trainPipe.pipe).SetCouplersPending(false); } } diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index ff2d4fe0e..424132c0c 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -49,9 +49,9 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) Sand = SandCapacity; // NOTE: for diesel-powered vehicles we automatically convert legacy "main" power source to more accurate "engine" - if (air.compressor.supply == CompressorSupply::mainCircuit && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric)) + if (air.compressor.config.supply == CompressorSupply::mainCircuit && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric)) { - air.compressor.supply = CompressorSupply::engine; + air.compressor.config.supply = CompressorSupply::engine; } // for these engine types secondary controller positions index MotorParam table @@ -96,8 +96,7 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) // set default wiper switch position wiperSwitchPos = WiperDefaultPos; - if (air.compressor.listPositions > 0) - air.compressor.listPosition = air.compressor.listDefaultPosition; + air.compressor.ResetListPosition(); // 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)) @@ -134,14 +133,14 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) if (brakes.independentValveType == TBrakeHandle::Knorr) brakes.independentPosition = 0.5; - brakePipe.reservoir->CreatePress(brakePipe.pressure); - mainPipe.reservoir->CreatePress(mainPipe.pressure); + brakePipe.reservoir->CreatePress(brakePipe.Pressure()); + mainPipe.reservoir->CreatePress(mainPipe.Pressure()); brakePipe.reservoir->Act(); mainPipe.reservoir->Act(); - brakes.equivalentPipePressure = brakePipe.pressure; + brakes.equivalentPipePressure = brakePipe.Pressure(); - brakes.driverValve->Init(brakePipe.pressure); + brakes.driverValve->Init(brakePipe.Pressure()); ComputeConstans(); @@ -188,7 +187,7 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) brakes.delays[b] = brakes.delays[b] * (2.5 + Random(0.0, 0.2)) / 3.0; } - brakes.distributor->Init(brakePipe.pressure, brakes.pipeHighPressure, brakes.pipeLowPressure, brakes.cylinderPressure, brakes.delaySetting); + brakes.distributor->Init(brakePipe.Pressure(), brakes.pipeHighPressure, brakes.pipeLowPressure, brakes.cylinderPressure, brakes.delaySetting); /* ScndPipePress = Compressor; */ @@ -406,9 +405,9 @@ void physics::Vehicle::CreateBrakePipes() // the pressure of the main pipe at the start: the main reservoir's, or HosePressure fed through a main hose, or none double physics::Vehicle::InitialScndPipePress(double const HosePressure) const { - if (air.mainReservoirVolume > 0.0) + if (air.config.mainReservoirVolume > 0.0) { - return air.compressedVolume / air.mainReservoirVolume; + return air.CompressedVolume() / air.config.mainReservoirVolume; } if (Couplers[VehicleEnd::front].AllowedFlag.HasAny(Coupling::mainHose) || Couplers[VehicleEnd::rear].AllowedFlag.HasAny(Coupling::mainHose)) { @@ -421,9 +420,9 @@ double physics::Vehicle::InitialScndPipePress(double const HosePressure) const void physics::Vehicle::SetReadyToDepart() { WriteLog("Ready to depart"); - air.compressedVolume = air.mainReservoirVolume * air.compressor.minPressure * 9.8 / 10.0; - mainPipe.pressure = InitialScndPipePress(5.0); - brakePipe.pressure = brakes.controlReservoirPressure; + air.Fill(air.config.mainReservoirVolume * air.compressor.config.minPressure * 9.8 / 10.0); + mainPipe.SetPressure(InitialScndPipePress(5.0)); + brakePipe.SetPressure(brakes.controlReservoirPressure); brakes.cylinderPressure = 0.0; brakes.independentPosition = 0.0; if (CabActive == 0) @@ -449,12 +448,12 @@ void physics::Vehicle::SetBraked() { WriteLog("Braked"); brakes.reservoirAir = brakes.valveVolume * brakes.maxCylinderPressure[3]; - air.compressedVolume = air.mainReservoirVolume * air.compressor.minPressure * 0.55; + air.Fill(air.config.mainReservoirVolume * air.compressor.config.minPressure * 0.55); /* ScndPipePress = 5.1; */ - mainPipe.pressure = InitialScndPipePress(5.1); - brakePipe.pressure = brakes.pipeLowPressure; + mainPipe.SetPressure(InitialScndPipePress(5.1)); + brakePipe.SetPressure(brakes.pipeLowPressure); brakes.pipeCylinderPressure = brakes.maxCylinderPressure[3] * 0.5; brakes.cylinderPressure = brakes.maxCylinderPressure[3] * 0.5; brakes.independentPosition = 0.0; diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index d00ea4a37..f6ab99ed5 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -113,7 +113,7 @@ double physics::Vehicle::Current(double n, double U) } // writepaslog("MotorCurrent ", FloatToStr(MotorCurrent)); - if (brakes.electrodynamic.type == dbrake_switch && (brakes.cylinderPressure > 2.0 || brakePipe.pressure < 3.6)) + if (brakes.electrodynamic.type == dbrake_switch && (brakes.cylinderPressure > 2.0 || brakePipe.Pressure() < 3.6)) { Im = 0; // Im:=0; diff --git a/physics/vehicle.h b/physics/vehicle.h index ba263d896..c6e4030eb 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -1524,7 +1524,7 @@ class Vehicle // (EmergencyBrakeMainOffPressure) while the master controller is on a power position bool EmergencyBrakeHoldsMainOff() const { - return lineBreaker.config.emergencyOffPressure > 0.0 && brakePipe.pressure < lineBreaker.config.emergencyOffPressure && false == IsMainCtrlNoPowerPos(); + return lineBreaker.config.emergencyOffPressure > 0.0 && brakePipe.Pressure() < lineBreaker.config.emergencyOffPressure && 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 @@ -1546,7 +1546,7 @@ class Vehicle // whether the pneumatic louvres of the motor fans are still closed, the main reservoir short of the pressure that opens them bool LouvresClosed() const { - return air.mainReservoirPressure < LouvresOpenPressure; + return air.MainReservoirPressure() < LouvresOpenPressure; } // whether the devices the line contactors are interlocked with (LineContactorsInterlock) let them close bool LineContactorsInterlockReleased() const; diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index ac38229b6..17cc92dad 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -75,7 +75,7 @@ std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle cons auto const on{[](bool const State, std::uint32_t const Bit) { return State ? Bit : 0u; }}; return on(Occupied.lowVoltage.IsBatteryOn() || Controlling.lowVoltage.IsBatteryOn(), device::battery) | on(Controlling.lineBreaker.IsClosed(), device::main_breaker) | on(Controlling.pantographs[VehicleEnd::front].is_active, device::pantograph_front) | on(Controlling.pantographs[VehicleEnd::rear].is_active, device::pantograph_rear) | - on(Controlling.converter.IsRunning(), device::converter) | on(Controlling.air.compressor.running, device::compressor) | on(Controlling.lineContactors.IsClosed(), device::line_contactors) | + on(Controlling.converter.IsRunning(), device::converter) | on(Controlling.air.compressor.IsRunning(), device::compressor) | on(Controlling.lineContactors.IsClosed(), device::line_contactors) | on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose, device::sanding) | on(Occupied.WarningSignal != 0, device::horn) | on(false == Occupied.Doors.instances[VehicleSide::left].is_closed, device::doors_left) | on(false == Occupied.Doors.instances[VehicleSide::right].is_closed, device::doors_right) | on(Occupied.Radio, device::radio) | @@ -453,12 +453,12 @@ void blackbox_recorder::write_cab() { sample.train_brake = static_cast(occupied->brakes.handlePositionSmooth); sample.local_brake = static_cast(occupied->brakes.independentPosition); sample.brake_cylinder = static_cast(occupied->brakes.cylinderPressure); - sample.brake_pipe = static_cast(occupied->brakePipe.pressure); + sample.brake_pipe = static_cast(occupied->brakePipe.Pressure()); sample.motor_current = static_cast(controlling->Im); if (owner != nullptr && owner->is_active()) sample.ai = owner->ai_reference(); sample.devices = devices_of(*occupied, *controlling); - sample.main_reservoir = static_cast(controlling->air.mainReservoirPressure); + sample.main_reservoir = static_cast(controlling->air.MainReservoirPressure()); sample.voltage = static_cast(controlling->EngineVoltage); sample.engine_rpm = static_cast(std::abs(controlling->enrot) * 60.0); // the lights at the ends of the train: of the vehicles at its ends, at their ends turned away from the rest @@ -478,7 +478,7 @@ void blackbox_recorder::write_cab() { // the const one: with no driver the first channel sample.radio_channel = static_cast(std::clamp(std::as_const(*train).RadioChannel(), 0, 255)); sample.driver_valve = occupied->brakes.driverValve != nullptr ? static_cast(occupied->brakes.driverValve->GetCP()) : 0.0f; - sample.feed_pipe = static_cast(occupied->mainPipe.pressure); + sample.feed_pipe = static_cast(occupied->mainPipe.Pressure()); sample.oil_pressure = controlling->OilPump.pressure; sample.water_temperature = controlling->diesel.heat.Twy; sample.oil_temperature = controlling->diesel.heat.To; diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 626f6752c..e0ec57730 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -467,7 +467,7 @@ void state_manager::process_commands() { if (commanddata.command == user_command::fillcompressor) { TDynamicObject *vehicle = simulation::Vehicles.find(commanddata.payload); - vehicle->physics->air.compressedVolume = 8.0f * vehicle->physics->air.mainReservoirVolume; + vehicle->physics->air.Fill(8.0f * vehicle->physics->air.config.mainReservoirVolume); } if (commanddata.command == user_command::dynamicmove) { diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index 04338f4c4..5e82d4e88 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -84,7 +84,7 @@ void consist::step(track const &Track, double Dt) { auto pipe{0.0}; auto length{0.0}; for (auto const &vehicle : m_vehicles) { - pipe += vehicle->physics().brakePipe.pressure * vehicle->physics().Dim.L; + pipe += vehicle->physics().brakePipe.Pressure() * vehicle->physics().Dim.L; length += vehicle->physics().Dim.L; } pipe /= length; diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index a76beee6a..ed6db3738 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -86,7 +86,7 @@ void release_brakes(physics::Vehicle &Cab) { bool is_ready(driven const &Driven) { auto const &physics{Driven.controlling}; - auto const air{physics.air.mainReservoirVolume <= 0.0 || physics.mainPipe.pressure >= 4.5}; + auto const air{physics.air.config.mainReservoirVolume <= 0.0 || physics.mainPipe.Pressure() >= 4.5}; // the converter feeds the 110 V circuits (the electrodynamic brake's control among them); the AI switches // it on once the line breaker is closed, so a train already charged with air isn't ready before it runs auto const converter{physics.converter.config.start != start_t::manual || physics.converter.IsRunning()}; @@ -114,7 +114,7 @@ void raise_pantographs(driven const &Driven) { } pantographs.pantographAir.SwitchCompressor(true); } - else if (false == pantographs.pantographAir.IsConnectedToMainReservoir() || pantographs.pantographAir.Pressure() <= pantographs.mainPipe.pressure) { + else if (false == pantographs.pantographAir.IsConnectedToMainReservoir() || pantographs.pantographAir.Pressure() <= pantographs.mainPipe.Pressure()) { pantographs.pantographAir.SwitchCompressor(false); } Driven.cab.OperatePantographsValve(operation_t::enable); @@ -210,7 +210,7 @@ void drive_cycle(driven Driven, track const &Track, trace &Trace) { auto &cab{Driven.cab}; auto &controlling{Driven.controlling}; if (false == start_up(Driven, Track, 300.0, &Trace)) { - MESSAGE("didn't get ready: Mains " << controlling.lineBreaker.IsClosed() << ", main reservoir " << controlling.mainPipe.pressure); + MESSAGE("didn't get ready: Mains " << controlling.lineBreaker.IsClosed() << ", main reservoir " << controlling.mainPipe.Pressure()); } Trace.mark("release brakes"); release_brakes(cab); diff --git a/tests/unit/figures.cpp b/tests/unit/figures.cpp index 7e9fd110e..f3325c0a2 100644 --- a/tests/unit/figures.cpp +++ b/tests/unit/figures.cpp @@ -62,7 +62,7 @@ constexpr double pipe_back{4.9}; void figures::sample(double Time, physics::Vehicle const &Vehicle) { auto &part{m_parts.back()}; auto const speed{Vehicle.V * 3.6}; - auto const pipe{Vehicle.brakePipe.pressure}; + auto const pipe{Vehicle.brakePipe.Pressure()}; if (false == part.sampled) { part.sampled = true; // from the last step of the part before, so the parts add up to the run diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index 21db64dd4..0e7c7a1bc 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -75,7 +75,7 @@ std::vector traction() { std::vector brakes() { return { {"BrakeCtrlPos", [](auto const &M) { return M.brakes.handlePosition; }}, - {"PipePress", [](auto const &M) { return M.brakePipe.pressure; }}, + {"PipePress", [](auto const &M) { return M.brakePipe.Pressure(); }}, {"BrakePress", [](auto const &M) { return M.brakes.cylinderPressure; }}, {"LocBrakePress", [](auto const &M) { return M.brakes.independentCylinderPressure; }}, {"BRP", [](auto const &M) { return M.brakes.distributor->GetBRP(); }}, @@ -86,9 +86,9 @@ std::vector brakes() { std::vector air() { return { - {"Compressor", [](auto const &M) { return M.air.mainReservoirPressure; }}, - {"CompressorFlag", [](auto const &M) { return M.air.compressor.running ? 1.0 : 0.0; }}, - {"ScndPipePress", [](auto const &M) { return M.mainPipe.pressure; }}, + {"Compressor", [](auto const &M) { return M.air.MainReservoirPressure(); }}, + {"CompressorFlag", [](auto const &M) { return M.air.compressor.IsRunning() ? 1.0 : 0.0; }}, + {"ScndPipePress", [](auto const &M) { return M.mainPipe.Pressure(); }}, }; } @@ -162,7 +162,7 @@ std::vector parameters() { {"CntrlPipePress", [](auto const &M) { return M.brakes.controlReservoirPressure; }}, {"BrakeVolume", [](auto const &M) { return M.brakes.cylinderVolume; }}, {"BrakeVVolume", [](auto const &M) { return M.brakes.valveVolume; }}, - {"VeselVolume", [](auto const &M) { return M.air.mainReservoirVolume; }}, + {"VeselVolume", [](auto const &M) { return M.air.config.mainReservoirVolume; }}, {"BrakeCylNo", [](auto const &M) { return M.brakes.cylinders.count; }}, {"BrakeCylRadius", [](auto const &M) { return M.brakes.cylinders.radius; }}, {"BrakeCylDist", [](auto const &M) { return M.brakes.cylinders.stroke; }}, @@ -172,11 +172,11 @@ std::vector parameters() { {"RapidMult", [](auto const &M) { return M.brakes.rapidRatio; }}, {"RapidVel", [](auto const &M) { return M.brakes.rapidSpeed; }}, {"BrakeValveSize", [](auto const &M) { return M.brakes.distributorSize; }}, - {"MinCompressor", [](auto const &M) { return M.air.compressor.minPressure; }}, - {"MaxCompressor", [](auto const &M) { return M.air.compressor.maxPressure; }}, - {"CompressorSpeed", [](auto const &M) { return M.air.compressor.speed; }}, + {"MinCompressor", [](auto const &M) { return M.air.compressor.config.minPressure; }}, + {"MaxCompressor", [](auto const &M) { return M.air.compressor.config.maxPressure; }}, + {"CompressorSpeed", [](auto const &M) { return M.air.compressor.config.speed; }}, {"EmergencyValveOn", [](auto const &M) { return M.brakes.emergencyValve.onPressure; }}, - {"AirLeakRate", [](auto const &M) { return M.air.leakRate; }}, + {"AirLeakRate", [](auto const &M) { return M.air.config.leakRate; }}, {"BrakeCtrlPosNo", [](auto const &M) { return M.brakes.handlePositions; }}, {"MainCtrlPosNo", [](auto const &M) { return M.MainCtrlPosNo; }}, {"ScndCtrlPosNo", [](auto const &M) { return M.ScndCtrlPosNo; }}, diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index c2ea5f029..cb2ad3c02 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -42,13 +42,13 @@ std::vector const &invariants() { {"every value a number", [](auto const &M, double, auto const *) { std::initializer_list const values{M.V, M.AccS, M.Ft, M.Fb, M.Im, M.Itot, M.EngineVoltage, - M.enrot, M.brakePipe.pressure, M.brakes.cylinderPressure, M.brakes.independentCylinderPressure, M.mainPipe.pressure, M.air.mainReservoirPressure, M.lowVoltage.BatteryVoltage()}; + M.enrot, M.brakePipe.Pressure(), M.brakes.cylinderPressure, M.brakes.independentCylinderPressure, M.mainPipe.Pressure(), M.air.MainReservoirPressure(), M.lowVoltage.BatteryVoltage()}; return std::ranges::all_of(values, [](double const Value) { return std::isfinite(Value); }); }, [](auto const &M) { return values({{"V", M.V}, {"AccS", M.AccS}, {"Ft", M.Ft}, {"Fb", M.Fb}, {"Im", M.Im}, {"Itot", M.Itot}, {"EngineVoltage", M.EngineVoltage}, - {"enrot", M.enrot}, {"PipePress", M.brakePipe.pressure}, {"BrakePress", M.brakes.cylinderPressure}, {"LocBrakePress", M.brakes.independentCylinderPressure}, - {"ScndPipePress", M.mainPipe.pressure}, {"Compressor", M.air.mainReservoirPressure}, {"BatteryVoltage", M.lowVoltage.BatteryVoltage()}}); + {"enrot", M.enrot}, {"PipePress", M.brakePipe.Pressure()}, {"BrakePress", M.brakes.cylinderPressure}, {"LocBrakePress", M.brakes.independentCylinderPressure}, + {"ScndPipePress", M.mainPipe.Pressure()}, {"Compressor", M.air.MainReservoirPressure()}, {"BatteryVoltage", M.lowVoltage.BatteryVoltage()}}); }}, {"brake cylinders between empty and the vehicle's highest pressure", [](auto const &M, double, auto const *) { @@ -61,14 +61,14 @@ std::vector const &invariants() { [](auto const &M, double, auto const *) { // all the air comes from the main reservoirs, which the game sets up to 10 bar, some (the Impuls) to 12; // the driver's valve in its filling position joins the brake pipe to them - auto const highest{1.01 * std::max(10.0, M.air.compressor.maxPressure) + pressure_margin}; - std::initializer_list const pressures{M.brakePipe.pressure, M.mainPipe.pressure, M.air.mainReservoirPressure}; + auto const highest{1.01 * std::max(10.0, M.air.compressor.config.maxPressure) + pressure_margin}; + std::initializer_list const pressures{M.brakePipe.Pressure(), M.mainPipe.Pressure(), M.air.MainReservoirPressure()}; return std::ranges::all_of(pressures, [highest](double const Press) { return Press >= -pressure_margin && Press <= highest; }); }, - [](auto const &M) { return values({{"PipePress", M.brakePipe.pressure}, {"ScndPipePress", M.mainPipe.pressure}, {"Compressor", M.air.mainReservoirPressure}}); }}, + [](auto const &M) { return values({{"PipePress", M.brakePipe.Pressure()}, {"ScndPipePress", M.mainPipe.Pressure()}, {"Compressor", M.air.MainReservoirPressure()}}); }}, {"main reservoir no higher than the compressor's governor", - [](auto const &M, double, auto const *) { return M.air.compressor.maxPressure <= 0.0 || M.air.mainReservoirPressure <= 1.01 * M.air.compressor.maxPressure + pressure_margin; }, - [](auto const &M) { return values({{"Compressor", M.air.mainReservoirPressure}, {"MaxCompressor", M.air.compressor.maxPressure}}); }}, + [](auto const &M, double, auto const *) { return M.air.compressor.config.maxPressure <= 0.0 || M.air.MainReservoirPressure() <= 1.01 * M.air.compressor.config.maxPressure + pressure_margin; }, + [](auto const &M) { return values({{"Compressor", M.air.MainReservoirPressure()}, {"MaxCompressor", M.air.compressor.config.maxPressure}}); }}, {"no motor current with the line breaker open", [](auto const &M, double, auto const *) { return M.lineBreaker.IsClosed() || false == electric(M) || std::abs(M.Im) < 1.0; }, [](auto const &M) { return values({{"Mains", M.lineBreaker.IsClosed()}, {"Im", M.Im}, {"Itot", M.Itot}}); }}, diff --git a/tests/unit/test_brake_handles.cpp b/tests/unit/test_brake_handles.cpp index 12d91adec..d7b6ba077 100644 --- a/tests/unit/test_brake_handles.cpp +++ b/tests/unit/test_brake_handles.cpp @@ -35,7 +35,7 @@ void hold(vehicle &Vehicle, test::trace &Trace, std::string const &Event, double // every position of the driver's handle, recorded in the trace void every_position(vehicle &Vehicle, test::trace &Trace) { - Vehicle.hold_main_reservoir(std::max(Vehicle->air.compressor.maxPressure, 8.0)); + Vehicle.hold_main_reservoir(std::max(Vehicle->air.compressor.config.maxPressure, 8.0)); REQUIRE(Vehicle->brakes.driverValve != nullptr); auto &handle{*Vehicle->brakes.driverValve}; Vehicle.record(Trace); @@ -102,7 +102,7 @@ TEST_CASE("brake handles: the local brake handle of every real vehicle") { if (false == has_handle(real)) { continue; } - real.hold_main_reservoir(std::max(real->air.compressor.maxPressure, 8.0)); + real.hold_main_reservoir(std::max(real->air.compressor.config.maxPressure, 8.0)); test::trace trace{"local brake/" + path, handle_channels(), 100}; real.record(trace); REQUIRE(real->brakes.driverValve != nullptr); @@ -133,22 +133,22 @@ TEST_CASE("brake handles: the overload and the high pressure buttons of the MHZ vehicle real{definition, 0.0, "test", 1}; real->BatterySwitch(true); real->CabActivisation(); - real.hold_main_reservoir(std::max(real->air.compressor.maxPressure, 8.0)); + real.hold_main_reservoir(std::max(real->air.compressor.config.maxPressure, 8.0)); test::trace trace{"brake handles/buttons/" + name, handle_channels(), 100}; real.record(trace); REQUIRE(real->brakes.driverValve != nullptr); auto &handle{*real->brakes.driverValve}; driven_at(real, trace, "running", handle.GetPos(bh_RP), 60.0); - auto const running{real->brakePipe.pressure}; + auto const running{real->brakePipe.Pressure()}; handle.SetUniversalFlag(TUniversalBrake::ub_Overload); driven_at(real, trace, "overload button", handle.GetPos(bh_RP), 30.0); handle.SetUniversalFlag(0); - auto const overloaded{real->brakePipe.pressure}; + auto const overloaded{real->brakePipe.Pressure()}; driven_at(real, trace, "overload decaying", handle.GetPos(bh_RP), 240.0); - auto const decayed{real->brakePipe.pressure}; + auto const decayed{real->brakePipe.Pressure()}; handle.SetUniversalFlag(TUniversalBrake::ub_HighPressure); driven_at(real, trace, "high pressure button, filling stroke", handle.GetPos(bh_FS), 10.0); - auto const filled{real->brakePipe.pressure}; + auto const filled{real->brakePipe.Pressure()}; handle.SetUniversalFlag(0); driven_at(real, trace, "running", handle.GetPos(bh_RP), 120.0); CHECK(running == doctest::Approx(5.0).epsilon(0.01)); @@ -283,10 +283,10 @@ std::vector st113_run() { vehicle real{definition::fiz("en57_v1/6bai")}; REQUIRE(real->brakes.driverValveType == TBrakeHandle::St113); REQUIRE(real->brakes.driverValve != nullptr); - real.hold_main_reservoir(std::max(real->air.compressor.maxPressure, 8.0)); + real.hold_main_reservoir(std::max(real->air.compressor.config.maxPressure, 8.0)); auto &handle{*real->brakes.driverValve}; std::vector samples; - auto const sample{[&] { samples.push_back({handle.GetCP(), real->brakePipe.pressure, real->brakes.cylinderPressure, handle.GetEP()}); }}; + auto const sample{[&] { samples.push_back({handle.GetCP(), real->brakePipe.Pressure(), real->brakes.cylinderPressure, handle.GetEP()}); }}; auto const hold{[&](double Position, std::initializer_list Seconds) { real->BrakeLevelSet(Position); for (auto const seconds : Seconds) { diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp index 6e7019afa..d2800784b 100644 --- a/tests/unit/test_brake_pipe.cpp +++ b/tests/unit/test_brake_pipe.cpp @@ -42,10 +42,10 @@ void passenger_train(test::consist &Train, int const Cars) { // 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->brakePipe.pressure}; + auto const start{last->brakePipe.Pressure()}; Train[0].hold_brake_pipe(Pressure); auto time{0.0}; - while (last->brakePipe.pressure > start - 0.5 && time < 60.0) { + while (last->brakePipe.Pressure() > start - 0.5 && time < 60.0) { Train.step({}, Dt); time += Dt; } @@ -72,8 +72,8 @@ TEST_CASE("brake pipe: the distributors of a standing freight train see the pres CAPTURE(i); auto &wagon{train[i].physics()}; // the distributor's valve chamber follows the pressure the distributor works with: the pipe's own - CHECK(std::abs(wagon.brakes.distributor->GetVRP() - wagon.brakePipe.pressure) < 0.005); - CHECK(wagon.brakePipe.pressure > 4.9); + CHECK(std::abs(wagon.brakes.distributor->GetVRP() - wagon.brakePipe.Pressure()) < 0.005); + CHECK(wagon.brakePipe.Pressure() > 4.9); // released, as the AI wants every vehicle before it starts (TController::CheckVehicles()) CHECK((wagon.brakes.distributor->GetBrakeStatus() & (b_on | b_hld)) == 0); CHECK(wagon.brakes.cylinderPressure < 0.1); @@ -106,7 +106,7 @@ TEST_CASE("brake pipe: a passenger train, whose exchange was stable in one step, for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); auto &car{train[i].physics()}; - CHECK(std::abs(car.brakes.distributor->GetVRP() - car.brakePipe.pressure) < 0.005); + CHECK(std::abs(car.brakes.distributor->GetVRP() - car.brakePipe.Pressure()) < 0.005); CHECK((car.brakes.distributor->GetBrakeStatus() & (b_on | b_hld)) == 0); CHECK(car.brakes.cylinderPressure < 0.1); } diff --git a/tests/unit/test_brakes.cpp b/tests/unit/test_brakes.cpp index 43ebdd098..1541cb9d3 100644 --- a/tests/unit/test_brakes.cpp +++ b/tests/unit/test_brakes.cpp @@ -114,14 +114,14 @@ TEST_CASE("brakes: a dead EN57 hauled with the brake hose alone charges from the car.brakePipe.reservoir->Act(); car.mainPipe.reservoir->CreatePress(0.0); car.mainPipe.reservoir->Act(); - car.air.compressedVolume = 0.0; + car.air.Fill(0.0); } locomotive.hold_brake_pipe(5.0); train.run(900.0); for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); auto &car{train[i].physics()}; - REQUIRE(car.mainPipe.pressure < 0.1); // no main reservoir pipe + REQUIRE(car.mainPipe.Pressure() < 0.1); // no main reservoir pipe CHECK(car.brakes.distributor->GetBRP() > 4.8); CHECK(car.brakes.distributor->GetCRP() > 4.8); CHECK(car.brakes.cylinderPressure < 0.1); diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index 2cbb7096d..a2b5faf5e 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -223,7 +223,7 @@ TEST_CASE("cab: the lamps and the buzzer of the security system left unattended" CHECK(blinked); CHECK(beeped); CHECK_FALSE(security.is_cabsignal_beeping()); - CHECK(eu07.brakePipe.pressure < 1.0); + CHECK(eu07.brakePipe.Pressure() < 1.0); CHECK(security.radiostop_available()); scenario.check(); } @@ -269,7 +269,7 @@ TEST_CASE("cab: the SM42's vigilance device switched off in the shunt mode, wher } CHECK(sm42.Vel > 1.0); CHECK_FALSE(blinked); - CHECK(sm42.brakePipe.pressure > 3.5); + CHECK(sm42.brakePipe.Pressure() > 3.5); scenario.act("shunt mode off"); scenario.notch_back(0); REQUIRE(sm42.CurrentSwitch(false)); @@ -293,7 +293,7 @@ TEST_CASE("cab: the vigilance device of the SM42 kept in the shunt mode, by defa scenario.act("unattended in shunt mode"); CHECK(unattended(scenario, 120)); CHECK(sm42.ShuntMode); - CHECK(sm42.brakePipe.pressure < 1.0); + CHECK(sm42.brakePipe.Pressure() < 1.0); scenario.check(); } @@ -324,7 +324,7 @@ TEST_CASE("cab: the SM42's vigilance alarm on, not cleared by switching into the CHECK(security.is_vigilance_blinking()); CHECK(security.is_beeping()); CHECK(security.is_braking()); - CHECK(sm42.brakePipe.pressure < 1.0); + CHECK(sm42.brakePipe.Pressure() < 1.0); scenario.act("acknowledged"); sm42.SecuritySystemReset(); scenario.train().run(1.0, scenario.line()); diff --git a/tests/unit/test_camshaft.cpp b/tests/unit/test_camshaft.cpp index 2c8a580d9..7231b2c5b 100644 --- a/tests/unit/test_camshaft.cpp +++ b/tests/unit/test_camshaft.cpp @@ -71,7 +71,7 @@ void running(physics::Vehicle &Locomotive, int const Direction, int const Positi Locomotive.CabActive = 1; Locomotive.DirActive = Direction; Locomotive.lineBreaker.Close(); - Locomotive.brakePipe.pressure = 5.0; // bar, the pressure switch lets the line contactors close + Locomotive.brakePipe.SetPressure(5.0); // bar, the pressure switch lets the line contactors close Locomotive.brakes.cylinderPressure = 0.0; Locomotive.lineContactors.Close(); Locomotive.MainCtrlActualPos = Position; diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index 68f652b7f..8566af2f9 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -55,8 +55,8 @@ std::vector state() { {"AutoRelayFlag", [](auto const &M) { return flag(M.AutoRelayFlag); }}, {"ConverterAllow", [](auto const &M) { return flag(M.converter.IsAllowed()); }}, {"Battery", [](auto const &M) { return flag(M.lowVoltage.IsBatteryOn()); }}, - {"CompressorAllow", [](auto const &M) { return flag(M.air.compressor.allow); }}, - {"CompressorListPos", [](auto const &M) { return M.air.compressor.listPosition; }}, + {"CompressorAllow", [](auto const &M) { return flag(M.air.compressor.IsAllowed()); }}, + {"CompressorListPos", [](auto const &M) { return M.air.compressor.ListPosition(); }}, {"DoorLock", [](auto const &M) { return flag(M.Doors.lock_enabled); }}, {"DoorStep", [](auto const &M) { return flag(M.Doors.step_enabled); }}, {"DoorRemoteOnly", [](auto const &M) { return flag(M.Doors.remote_only); }}, @@ -413,8 +413,8 @@ TEST_CASE("commands: every switch of the cab, worked on a pair standing under th {"PantPress", [](auto const &M) { return M.pantographAir.Pressure(); }}, {"GroundRelay", [](auto const &M) { return flag(M.protection.GroundHolds()); }}, {"ConverterFlag", [](auto const &M) { return flag(M.converter.IsRunning()); }}, - {"CompressorFlag", [](auto const &M) { return flag(M.air.compressor.running); }}, - {"Compressor", [](auto const &M) { return M.air.mainReservoirPressure; }}, + {"CompressorFlag", [](auto const &M) { return flag(M.air.compressor.IsRunning()); }}, + {"Compressor", [](auto const &M) { return M.air.MainReservoirPressure(); }}, {"MainCtrlActualPos", [](auto const &M) { return M.MainCtrlActualPos; }}, {"Itot", [](auto const &M) { return M.Itot; }}, {"FuseFlag", [](auto const &M) { return flag(M.FuseFlag); }}, diff --git a/tests/unit/test_compressor.cpp b/tests/unit/test_compressor.cpp index b4bc1a201..5694f2d65 100644 --- a/tests/unit/test_compressor.cpp +++ b/tests/unit/test_compressor.cpp @@ -26,7 +26,7 @@ vehicle compressor_vehicle(double const Delay, std::string const &Power = "Main" definition.set("Brake", "CompressorStartDelay", Delay); } vehicle vehicle{definition}; - vehicle->air.compressedVolume = 0.0; + vehicle->air.Fill(0.0); vehicle->LastSwitchingTime = 10.0; // nothing was switched lately return vehicle; } @@ -45,11 +45,11 @@ void run_compressor(vehicle &Vehicle, double const Seconds) { TEST_CASE("compressor: without a start delay the compressor starts with its power") { auto vehicle{compressor_vehicle(0.0)}; run_compressor(vehicle, 1.0); - REQUIRE_FALSE(vehicle->air.compressor.running); // no power, no compressor + REQUIRE_FALSE(vehicle->air.compressor.IsRunning()); // no power, no compressor vehicle->lineBreaker.Close(); run_compressor(vehicle, step); - CHECK(vehicle->air.compressor.running); + CHECK(vehicle->air.compressor.IsRunning()); } TEST_CASE("compressor: the compressor starts the delay after getting its power") { @@ -57,94 +57,94 @@ TEST_CASE("compressor: the compressor starts the delay after getting its power") vehicle->lineBreaker.Close(); run_compressor(vehicle, 4.9); - CHECK_FALSE(vehicle->air.compressor.running); - CHECK(vehicle->air.mainReservoirPressure == doctest::Approx(0.0)); + CHECK_FALSE(vehicle->air.compressor.IsRunning()); + CHECK(vehicle->air.MainReservoirPressure() == doctest::Approx(0.0)); run_compressor(vehicle, 0.2); - CHECK(vehicle->air.compressor.running); + CHECK(vehicle->air.compressor.IsRunning()); run_compressor(vehicle, 10.0); - CHECK(vehicle->air.mainReservoirPressure > 0.0); // and fills the reservoir + CHECK(vehicle->air.MainReservoirPressure() > 0.0); // and fills the reservoir } TEST_CASE("compressor: the delay starts over once the power is gone") { auto vehicle{compressor_vehicle(5.0)}; vehicle->lineBreaker.Close(); run_compressor(vehicle, 10.0); - REQUIRE(vehicle->air.compressor.running); + REQUIRE(vehicle->air.compressor.IsRunning()); vehicle->lineBreaker.Open(); // the engine stopped run_compressor(vehicle, 1.0); - CHECK_FALSE(vehicle->air.compressor.running); + CHECK_FALSE(vehicle->air.compressor.IsRunning()); vehicle->lineBreaker.Close(); // and started again run_compressor(vehicle, 4.9); - CHECK_FALSE(vehicle->air.compressor.running); + CHECK_FALSE(vehicle->air.compressor.IsRunning()); run_compressor(vehicle, 0.2); - CHECK(vehicle->air.compressor.running); + CHECK(vehicle->air.compressor.IsRunning()); } TEST_CASE("compressor: a compressor fed from the low voltage waits from the low voltage coming on") { auto vehicle{compressor_vehicle(5.0, "")}; // the default supply: the converter, the 110 V vehicle->lineBreaker.Close(); // which alone doesn't feed it run_compressor(vehicle, 10.0); - REQUIRE_FALSE(vehicle->air.compressor.running); + REQUIRE_FALSE(vehicle->air.compressor.IsRunning()); vehicle->lowVoltage.Set110vAvailableForTest(true); run_compressor(vehicle, 4.9); - CHECK_FALSE(vehicle->air.compressor.running); + CHECK_FALSE(vehicle->air.compressor.IsRunning()); run_compressor(vehicle, 0.2); - CHECK(vehicle->air.compressor.running); + CHECK(vehicle->air.compressor.IsRunning()); } TEST_CASE("compressor: the pressure switch stops the compressor above the cut-out pressure") { auto vehicle{compressor_vehicle(0.0)}; vehicle->lineBreaker.Close(); - vehicle->air.compressedVolume = 8.5; // over MaxCP, in the reservoir of 1 m3 + vehicle->air.Fill(8.5); // over MaxCP, in the reservoir of 1 m3 run_compressor(vehicle, step); - CHECK(vehicle->air.compressor.governorLock); - CHECK_FALSE(vehicle->air.compressor.running); + CHECK(vehicle->air.compressor.IsGovernorLocked()); + CHECK_FALSE(vehicle->air.compressor.IsRunning()); } TEST_CASE("compressor: without a pressure switch the air over the cut-out pressure is vented") { auto vehicle{compressor_vehicle(0.0, "Main", 8.0)}; // MinCP the same as MaxCP: no pressure switch vehicle->lineBreaker.Close(); - vehicle->air.compressedVolume = 8.5; + vehicle->air.Fill(8.5); run_compressor(vehicle, step); - REQUIRE(vehicle->air.compressor.running); // nothing stops it - CHECK(vehicle->air.compressedVolume < 8.5 * 0.81); // a fifth of the air let out + REQUIRE(vehicle->air.compressor.IsRunning()); // nothing stops it + CHECK(vehicle->air.CompressedVolume() < 8.5 * 0.81); // a fifth of the air let out } TEST_CASE("compressor: an engine stopped before the delay passed counts the whole delay again") { auto vehicle{compressor_vehicle(30.0)}; vehicle->lineBreaker.Close(); // engine started run_compressor(vehicle, 20.0); - REQUIRE_FALSE(vehicle->air.compressor.running); + REQUIRE_FALSE(vehicle->air.compressor.IsRunning()); vehicle->lineBreaker.Open(); // engine stopped, 10 s short of the delay run_compressor(vehicle, 1.0); vehicle->lineBreaker.Close(); run_compressor(vehicle, 15.0); // 36 s since the first start, but only 15 s since this one - CHECK_FALSE(vehicle->air.compressor.running); + CHECK_FALSE(vehicle->air.compressor.IsRunning()); run_compressor(vehicle, 15.1); - CHECK(vehicle->air.compressor.running); + CHECK(vehicle->air.compressor.IsRunning()); } TEST_CASE("compressor: the start delay holds back a compressor switched on by hand too") { auto vehicle{compressor_vehicle(30.0)}; - vehicle->air.compressor.start = start_t::manual; - vehicle->air.compressor.allow = true; // switch in the cabinet on before the engine start + vehicle->air.compressor.config.start = start_t::manual; + vehicle->air.compressor.Allow(true); // switch in the cabinet on before the engine start vehicle->lineBreaker.Close(); run_compressor(vehicle, 29.9); - CHECK_FALSE(vehicle->air.compressor.running); + CHECK_FALSE(vehicle->air.compressor.IsRunning()); run_compressor(vehicle, 0.2); - CHECK(vehicle->air.compressor.running); + CHECK(vehicle->air.compressor.IsRunning()); } TEST_CASE("compressor: the start delay is read from the brake section") { auto const delay{[](std::string const &Section) { - return vehicle{definition::load("wagon").set(Section, "CompressorStartDelay", 30)}->air.compressor.startDelay; + return vehicle{definition::load("wagon").set(Section, "CompressorStartDelay", 30)}->air.compressor.config.startDelay; }}; CHECK(delay("Brake") == doctest::Approx(30.0)); CHECK(delay("Cntrl") == doctest::Approx(0.0)); // the key isn't taken from the control section @@ -174,7 +174,7 @@ definition generator_vehicle(double const ConverterDelay, double const Compresso TEST_CASE("compressor: fed from the converter it waits for the converter start delay") { vehicle loco{generator_vehicle(30.0, 0.0)}; - REQUIRE(loco->air.compressor.supply == physics::CompressorSupply::converter); + REQUIRE(loco->air.compressor.config.supply == physics::CompressorSupply::converter); REQUIRE(loco->converter.config.startDelay == doctest::Approx(30.0)); loco.run(1.0); // engine off @@ -183,23 +183,23 @@ TEST_CASE("compressor: fed from the converter it waits for the converter start d loco->lineBreaker.Close(); // engine started loco.run(25.0); CHECK_FALSE(loco->lowVoltage.Is110vAvailable()); - CHECK_FALSE(loco->air.compressor.running); + CHECK_FALSE(loco->air.compressor.IsRunning()); loco.run(10.0); CHECK(loco->lowVoltage.Is110vAvailable()); - CHECK(loco->air.compressor.running); + CHECK(loco->air.compressor.IsRunning()); } TEST_CASE("compressor: fed from the converter the start delay counts from the converter voltage") { vehicle loco{generator_vehicle(20.0, 10.0)}; - REQUIRE(loco->air.compressor.startDelay == doctest::Approx(10.0)); + REQUIRE(loco->air.compressor.config.startDelay == doctest::Approx(10.0)); loco.run(1.0); // engine off loco->lineBreaker.Close(); // engine started loco.run(25.0); REQUIRE(loco->lowVoltage.Is110vAvailable()); // the converter is up - CHECK_FALSE(loco->air.compressor.running); // but the compressor waits for its own delay as well + CHECK_FALSE(loco->air.compressor.IsRunning()); // but the compressor waits for its own delay as well loco.run(10.0); - CHECK(loco->air.compressor.running); + CHECK(loco->air.compressor.IsRunning()); } diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index 6d853f799..0879c2fae 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -301,16 +301,16 @@ TEST_CASE("controls: emergency stops by the alarm chain and the radio-stop") { scenario.wait(40.0); // the pipe emptied, the whole train braked to a stop CHECK(stopped(scenario)); - CHECK(cab.brakePipe.pressure < 0.5); + CHECK(cab.brakePipe.Pressure() < 0.5); CHECK(scenario.vehicle(2).brakes.cylinderPressure > 1.0); scenario.act("alarm chain reset"); scenario.vehicle(1).AlarmChainSwitch(false); scenario.wait(10.0); // the FV4a handle stays cut off the emptied pipe of an LSt locomotive (lock_old in UpdatePipePressure) // until the releaser is held - CHECK(cab.brakePipe.pressure < 0.5); + CHECK(cab.brakePipe.Pressure() < 0.5); recharge(scenario); - CHECK(cab.brakePipe.pressure > 4.5); + CHECK(cab.brakePipe.Pressure() > 4.5); scenario.get_going(); notch_up(scenario, 20, 1.0); scenario.wait(20.0); @@ -320,12 +320,12 @@ TEST_CASE("controls: emergency stops by the alarm chain and the radio-stop") { cab.RadiostopSwitch(true); scenario.wait(40.0); CHECK(stopped(scenario)); - CHECK(cab.brakePipe.pressure < 0.5); + CHECK(cab.brakePipe.Pressure() < 0.5); scenario.act("radio-stop reset"); cab.RadiostopSwitch(false); scenario.wait(10.0); recharge(scenario); - CHECK(cab.brakePipe.pressure > 4.5); + CHECK(cab.brakePipe.Pressure() > 4.5); scenario.check(); } @@ -353,7 +353,7 @@ TEST_CASE("controls: releasers and the universal brake buttons") { CHECK(cab.brakes.cylinderPressure < 0.5); CHECK(coach.brakes.cylinderPressure < coachbraked - 1.0); CHECK(wagon.brakes.cylinderPressure < wagonbraked - 0.5); - CHECK(cab.brakePipe.pressure < 4.0); // the pipe stays where the service application left it + CHECK(cab.brakePipe.Pressure() < 4.0); // the pipe stays where the service application left it wagonbraked = wagon.brakes.cylinderPressure; scenario.act("releaser of the wagon"); wagon.BrakeReleaser(1); @@ -370,7 +370,7 @@ TEST_CASE("controls: releasers and the universal brake buttons") { scenario.act("running"); cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_RP)); scenario.wait(60.0); - CHECK(cab.brakePipe.pressure > 4.8); + CHECK(cab.brakePipe.Pressure() > 4.8); CHECK(released(scenario)); scenario.check(); } @@ -403,7 +403,7 @@ TEST_CASE("controls: the ep brake of electric units") { if (i == 3) { // the ep brake works the cylinders of every car by wire, the pipe stays charged (by the first // application the EW58's pipe is still charging after the start-up) - CHECK(cab.brakePipe.pressure > 4.8); + CHECK(cab.brakePipe.Pressure() > 4.8); CHECK(cab.brakes.cylinderPressure > 1.0); CHECK(last.brakes.cylinderPressure > 1.0); } diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp index 042f02c39..1ebcc03c9 100644 --- a/tests/unit/test_crew.cpp +++ b/tests/unit/test_crew.cpp @@ -208,7 +208,7 @@ TEST_CASE("crew: a locomotive under power left by its driver stops and stays bra auto const stoppedafter{seconds_to_stop(train, 120.0)}; CAPTURE(stoppedafter); CHECK(std::abs(train[0].speed()) <= 0.01); - CHECK(eu07.brakePipe.pressure < 1.0); // vented by the emergency position + CHECK(eu07.brakePipe.Pressure() < 1.0); // vented by the emergency position CHECK(eu07.brakes.cylinderPressure > 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}); @@ -252,7 +252,7 @@ TEST_CASE("crew: a train left by its driver is braked through the whole of it") CAPTURE(stoppedafter); CHECK(std::abs(train[0].speed()) <= 0.01); CHECK(std::abs(train[2].speed()) <= 0.01); - CHECK(last.brakePipe.pressure < 1.0); + CHECK(last.brakePipe.Pressure() < 1.0); CHECK(last.brakes.cylinderPressure > 1.0); } diff --git a/tests/unit/test_definition.cpp b/tests/unit/test_definition.cpp index bed2aba2f..6c9deb7d3 100644 --- a/tests/unit/test_definition.cpp +++ b/tests/unit/test_definition.cpp @@ -76,32 +76,32 @@ TEST_CASE("definition: a compressor list, whose positions allow the compressor a .set("CompressorList", "Default", 1) .set("CompressorList", "rows", {{2, 2, 1, 1}, {1, 1, 1, 1}, {2, 1, 0.9, 0.9}})}; vehicle real{eu07, 0.0, "test", 1}; - CHECK(real->air.compressor.listPositions == 3); - CHECK(real->air.compressor.list[3][3] == 0); + CHECK(real->air.compressor.config.listPositions == 3); + CHECK(real->air.compressor.config.list[3][3] == 0); auto driven{test::driving(real)}; test::track const line{0.15, 0.0, test::catenary_3kv}; REQUIRE(test::start_up(driven, line)); - CHECK(real->air.compressor.listPosition == 1); + CHECK(real->air.compressor.ListPosition() == 1); test::drive(driven, line, 60.0); - CHECK(real->air.compressor.allow); - CHECK(real->air.mainReservoirPressure <= real->air.compressor.maxPressure + 0.05); - CHECK(real->air.mainReservoirPressure >= real->air.compressor.minPressure - 0.05); + CHECK(real->air.compressor.IsAllowed()); + CHECK(real->air.MainReservoirPressure() <= real->air.compressor.config.maxPressure + 0.05); + CHECK(real->air.MainReservoirPressure() >= real->air.compressor.config.minPressure - 0.05); // the second position doesn't let it run CHECK(real->ChangeCompressorPreset(2)); test::drive(driven, line, 2.0); - CHECK_FALSE(real->air.compressor.allow); - CHECK_FALSE(real->air.compressor.running); + CHECK_FALSE(real->air.compressor.IsAllowed()); + CHECK_FALSE(real->air.compressor.IsRunning()); // the third lets it, under limits of nothing: with no span between them for the governor, the reservoir over // the upper limit gets vented while the compressor runs on CHECK(real->ChangeCompressorPreset(3)); - auto const full{real->air.mainReservoirPressure}; + auto const full{real->air.MainReservoirPressure()}; test::drive(driven, line, 10.0); - CHECK(real->air.compressor.allow); - CHECK(real->air.compressor.running); - CHECK(real->air.mainReservoirPressure < full - 1.0); + CHECK(real->air.compressor.IsAllowed()); + CHECK(real->air.compressor.IsRunning()); + CHECK(real->air.MainReservoirPressure() < full - 1.0); // no further than the last position CHECK_FALSE(real->ChangeCompressorPreset(5)); - CHECK(real->air.compressor.listPosition == 3); + CHECK(real->air.compressor.ListPosition() == 3); } TEST_CASE("definition: the compressor's limits set apart for the rear cab") { @@ -113,11 +113,11 @@ TEST_CASE("definition: the compressor's limits set apart for the rear cab") { test::track const line{0.15, 0.0, test::catenary_3kv}; REQUIRE(test::start_up(driven, line)); test::drive(driven, line, 120.0); - CHECK(real->air.compressor.cabDependent); - CHECK(real->air.compressor.maxPressure == doctest::Approx(cab > 0 ? 8.7 : 6.0)); - CHECK(real->air.compressor.minPressure == doctest::Approx(cab > 0 ? 7.0 : 5.0)); - CHECK(real->air.mainReservoirPressure <= real->air.compressor.maxPressure + 0.05); - CHECK(real->air.mainReservoirPressure >= real->air.compressor.minPressure - 0.05); + CHECK(real->air.compressor.config.cabDependent); + CHECK(real->air.compressor.config.maxPressure == doctest::Approx(cab > 0 ? 8.7 : 6.0)); + CHECK(real->air.compressor.config.minPressure == doctest::Approx(cab > 0 ? 7.0 : 5.0)); + CHECK(real->air.MainReservoirPressure() <= real->air.compressor.config.maxPressure + 0.05); + CHECK(real->air.MainReservoirPressure() >= real->air.compressor.config.minPressure - 0.05); } } diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp index a5ed0ece1..0f7f084de 100644 --- a/tests/unit/test_dynamic_brake_diesel.cpp +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -227,7 +227,7 @@ TEST_CASE("diesel-electric dynamic brake: blended with the locomotive's air brak scenario.wait(6.0); REQUIRE(locomotive.Vel > 15.0); CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); - CHECK(locomotive.brakePipe.pressure < 4.6); + CHECK(locomotive.brakePipe.Pressure() < 4.6); CHECK((locomotive.brakes.cylinderPressure < 0.2) == blending); scenario.check(); } diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index c2d3847aa..c89d56ee5 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -61,7 +61,7 @@ struct elf { } test::release_brakes(cab()); recharge(); - charged = cab().brakePipe.pressure > 4.5; + charged = cab().brakePipe.Pressure() > 4.5; } // the pipe charged again after an emergency stop: the Elf locks its emptied pipe off the brake handle (LPOn, // LPOff) until the unlock button (UBB1, the first universal brake button) is held, the handle at running @@ -105,7 +105,7 @@ TEST_CASE("elf controller: without EIMCtrlMainEmergency the positions stay as th CHECK_FALSE(physics.IsMainCtrlEmergencyPos()); unit.wait(10.0); CHECK(physics.eimic == doctest::Approx(-1.0)); - CHECK(physics.brakePipe.pressure > 4.5); + CHECK(physics.brakePipe.Pressure() > 4.5); } TEST_CASE("elf controller: EIMCtrlMainEmergency shifts the positions up by the emergency brake one") { @@ -127,14 +127,14 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency shifts the positions up by the e physics.MainCtrlPos = 1; unit.wait(10.0); CHECK(physics.eimic == doctest::Approx(-1.0)); - CHECK(physics.brakePipe.pressure > 4.5); + CHECK(physics.brakePipe.Pressure() > 4.5); } SUBCASE("the braking position, formerly 1, ramps the braking up") { physics.MainCtrlPos = 2; unit.wait(1.0); CHECK(physics.eimic < 0.0); CHECK(physics.eimic > -1.0); - CHECK(physics.brakePipe.pressure > 4.5); + CHECK(physics.brakePipe.Pressure() > 4.5); } SUBCASE("the emergency brake position brakes fully at once and empties the pipe") { physics.MainCtrlPos = 0; @@ -143,13 +143,13 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency shifts the positions up by the e unit.unit.step(unit.line); CHECK(physics.eimic == doctest::Approx(-1.0)); unit.wait(10.0); - CHECK(physics.brakePipe.pressure < 0.5); + CHECK(physics.brakePipe.Pressure() < 0.5); CHECK(physics.brakes.cylinderPressure > 1.0); // out of it the pipe charges again physics.MainCtrlPos = physics.MainCtrlNoPowerPos(); CHECK_FALSE(physics.IsMainCtrlEmergencyPos()); unit.recharge(); - CHECK(physics.brakePipe.pressure > 4.5); + CHECK(physics.brakePipe.Pressure() > 4.5); } } @@ -195,8 +195,8 @@ TEST_CASE("elf controller: the emergency brake position vents the pipe only from CHECK(rear.IsMainCtrlEmergencyPos()); CHECK_FALSE(rear.IsCabMaster()); unit.wait(10.0); - CHECK(unit.cab().brakePipe.pressure > 4.5); - CHECK(rear.brakePipe.pressure > 4.5); + CHECK(unit.cab().brakePipe.Pressure() > 4.5); + CHECK(rear.brakePipe.Pressure() > 4.5); } TEST_CASE("elf controller: an Elf with the emergency brake position leading one without it") { @@ -217,15 +217,15 @@ TEST_CASE("elf controller: an Elf with the emergency brake position leading one unit.set_controller(1); CHECK(other.MainCtrlPos == 0); unit.wait(10.0); - CHECK(lead.brakePipe.pressure > 4.5); + CHECK(lead.brakePipe.Pressure() > 4.5); } SUBCASE("the emergency brake: the other one at its full braking, the pipe vented by the lead") { unit.set_controller(0); REQUIRE(lead.IsMainCtrlEmergencyPos()); CHECK(other.MainCtrlPos == 0); unit.wait(10.0); - CHECK(lead.brakePipe.pressure < 0.5); - CHECK(other.brakePipe.pressure < 0.5); + CHECK(lead.brakePipe.Pressure() < 0.5); + CHECK(other.brakePipe.Pressure() < 0.5); } } @@ -247,8 +247,8 @@ TEST_CASE("elf controller: an Elf without the emergency brake position leading o CHECK(other.MainCtrlPos == 1); CHECK_FALSE(other.IsMainCtrlEmergencyPos()); unit.wait(10.0); - CHECK(lead.brakePipe.pressure > 4.5); - CHECK(other.brakePipe.pressure > 4.5); + CHECK(lead.brakePipe.Pressure() > 4.5); + CHECK(other.brakePipe.Pressure() > 4.5); } } diff --git a/tests/unit/test_feed_pipe.cpp b/tests/unit/test_feed_pipe.cpp index a7eba7c0c..50a7441de 100644 --- a/tests/unit/test_feed_pipe.cpp +++ b/tests/unit/test_feed_pipe.cpp @@ -48,7 +48,7 @@ double off_pressure(test::consist &Train, double const Pressure, double const Se 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]->mainPipe.pressure - Pressure)); + off = std::max(off, std::abs(Train[i]->mainPipe.Pressure() - Pressure)); } } return off; @@ -67,13 +67,13 @@ evening_out even_out(Builder Train, int const Count, double const Pressure, doub Train(train, Count); for (std::size_t i = 0; i < train.size(); ++i) { auto &physics{train[i].physics()}; - REQUIRE(physics.air.mainReservoirVolume > 0.0); + REQUIRE(physics.air.config.mainReservoirVolume > 0.0); auto const pressure{i == 0 ? Pressure : Pressure - 1.0}; - physics.air.compressedVolume = pressure * physics.air.mainReservoirVolume; - physics.air.mainReservoirPressure = pressure; + physics.air.Fill(pressure * physics.air.config.mainReservoirVolume); + physics.air.SetPressureForTest(pressure); physics.mainPipe.reservoir->CreatePress(pressure); physics.mainPipe.reservoir->Act(); - physics.mainPipe.pressure = pressure; + physics.mainPipe.SetPressure(pressure); } evening_out result; auto const &first{train[0].physics()}; @@ -81,22 +81,22 @@ evening_out even_out(Builder Train, int const Count, double const Pressure, doub std::vector previous(train.size()); std::vector change(train.size()); for (std::size_t i = 0; i < train.size(); ++i) { - previous[i] = train[i]->mainPipe.pressure; + previous[i] = train[i]->mainPipe.Pressure(); } 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]->mainPipe.pressure - previous[i]}; + auto const step{train[i]->mainPipe.Pressure() - 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]->mainPipe.pressure; + previous[i] = train[i]->mainPipe.Pressure(); } - if (std::abs(first.air.mainReservoirPressure - last.air.mainReservoirPressure) < 0.05) { + if (std::abs(first.air.MainReservoirPressure() - last.air.MainReservoirPressure()) < 0.05) { result.time = time; break; } @@ -113,15 +113,15 @@ double charging_time(Builder Train, int const Count, double const Pressure, doub train[0].hold_main_reservoir(Pressure); for (std::size_t i = 1; i < train.size(); ++i) { auto &physics{train[i].physics()}; - REQUIRE(physics.air.mainReservoirVolume == 0.0); + REQUIRE(physics.air.config.mainReservoirVolume == 0.0); physics.mainPipe.reservoir->CreatePress(0.0); physics.mainPipe.reservoir->Act(); - physics.mainPipe.pressure = 0.0; + physics.mainPipe.SetPressure(0.0); } auto const &first{train[0].physics()}; auto const &last{train[train.size() - 1].physics()}; auto time{0.0}; - while ((last.mainPipe.pressure < 1.0 || std::abs(last.mainPipe.pressure - first.mainPipe.pressure) > 0.2) && time < 60.0) { + while ((last.mainPipe.Pressure() < 1.0 || std::abs(last.mainPipe.Pressure() - first.mainPipe.Pressure()) > 0.2) && time < 60.0) { train.step({}, Dt); time += Dt; } diff --git a/tests/unit/test_figures.cpp b/tests/unit/test_figures.cpp index 718d722f7..7eb7429c9 100644 --- a/tests/unit/test_figures.cpp +++ b/tests/unit/test_figures.cpp @@ -17,21 +17,21 @@ TEST_CASE("figures: a run split into parts by the events, each from the last ste test::figures figures; auto &physics{eu07.physics()}; physics.V = 10.0; - physics.brakePipe.pressure = 5.0; + physics.brakePipe.SetPressure(5.0); figures.sample(0.0, physics); figures.mark("brake"); figures.mark("hard"); for (int i = 1; i <= 10; ++i) { physics.V = 10.0 - i; physics.DistCounter += 0.005; - physics.brakePipe.pressure = 3.5; + physics.brakePipe.SetPressure(3.5); physics.brakes.cylinderPressure = 0.4 * i; figures.sample(i, physics); } figures.mark("release"); - physics.brakePipe.pressure = 4.0; + physics.brakePipe.SetPressure(4.0); figures.sample(11.0, physics); - physics.brakePipe.pressure = 5.0; + physics.brakePipe.SetPressure(5.0); figures.sample(12.0, physics); auto const lines{figures.lines()}; diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index 695f45193..ca2dc48a8 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -90,7 +90,7 @@ bool start_on_genset(vehicle &Vehicle, track const &Track = no_wire, double cons cab.CompressorSwitch(true); } run(Vehicle, 1.0, Track); - if (cab.lineBreaker.IsClosed() && cab.converter.IsRunning() && cab.mainPipe.pressure >= 4.5) { + if (cab.lineBreaker.IsClosed() && cab.converter.IsRunning() && cab.mainPipe.Pressure() >= 4.5) { // and the brakes let go test::release_brakes(cab); for (auto wait = 0; wait < 120 && cab.brakes.cylinderPressure > 0.05; ++wait) { diff --git a/tests/unit/test_horn.cpp b/tests/unit/test_horn.cpp index 021531986..65c600944 100644 --- a/tests/unit/test_horn.cpp +++ b/tests/unit/test_horn.cpp @@ -57,19 +57,19 @@ TEST_CASE("horn: a pneumatic horn sounds on the air of the main reservoir only") auto vehicle{horn_vehicle(test::definition::load("wagon"))}; REQUIRE(vehicle->HornSupply == horn_supply::air); // the default - vehicle->air.mainReservoirPressure = 6.5; + vehicle->air.SetPressureForTest(6.5); CHECK(vehicle->SoundingHorns(allhorns) == allhorns); - vehicle->air.mainReservoirPressure = 0.0; // the reservoir is empty + vehicle->air.SetPressureForTest(0.0); // the reservoir is empty CHECK(vehicle->SoundingHorns(allhorns) == 0); } TEST_CASE("horn: a vehicle without a main reservoir takes the horn air from the main pipe") { test::vehicle vehicle{test::definition::load("wagon")}; - REQUIRE(vehicle->air.mainReservoirVolume == 0.0); + REQUIRE(vehicle->air.config.mainReservoirVolume == 0.0); - vehicle->mainPipe.pressure = 5.0; + vehicle->mainPipe.SetPressure(5.0); CHECK(vehicle->SoundingHorns(horn::low) == horn::low); - vehicle->mainPipe.pressure = 0.0; + vehicle->mainPipe.SetPressure(0.0); CHECK(vehicle->SoundingHorns(horn::low) == 0); } @@ -78,7 +78,7 @@ TEST_CASE("horn: an electric horn sounds on the low voltage, whatever the air") REQUIRE(vehicle->HornSupply == horn_supply::electric); REQUIRE(vehicle->Horn3Supply == horn_supply::electric); // the third horn follows the others unless told otherwise - vehicle->air.mainReservoirPressure = 0.0; + vehicle->air.SetPressureForTest(0.0); vehicle->lowVoltage.Set24vAvailableForTest(true); CHECK(vehicle->SoundingHorns(allhorns) == allhorns); vehicle->lowVoltage.Set24vAvailableForTest(false); @@ -90,10 +90,10 @@ TEST_CASE("horn: the third horn can have a supply of its own, an electric horn o REQUIRE(vehicle->HornSupply == horn_supply::air); REQUIRE(vehicle->Horn3Supply == horn_supply::electric); - vehicle->air.mainReservoirPressure = 0.0; + vehicle->air.SetPressureForTest(0.0); vehicle->lowVoltage.Set24vAvailableForTest(true); CHECK(vehicle->SoundingHorns(allhorns) == 4); - vehicle->air.mainReservoirPressure = 6.5; + vehicle->air.SetPressureForTest(6.5); vehicle->lowVoltage.Set24vAvailableForTest(false); CHECK(vehicle->SoundingHorns(allhorns) == (horn::low | horn::high)); } @@ -101,16 +101,16 @@ TEST_CASE("horn: the third horn can have a supply of its own, an electric horn o TEST_CASE("horn: a vehicle without any air, a road vehicle say, sounds its pneumatic horn as before") { // no main reservoir and no main pipe connection at either end test::vehicle vehicle{test::definition::load("wagon").set("BuffCoupl", "AllowedFlag", 3)}; - REQUIRE(vehicle->air.mainReservoirVolume == 0.0); - vehicle->mainPipe.pressure = 0.0; + REQUIRE(vehicle->air.config.mainReservoirVolume == 0.0); + vehicle->mainPipe.SetPressure(0.0); CHECK(vehicle->SoundingHorns(allhorns) == allhorns); } TEST_CASE("horn: a pneumatic horn sounds from the threshold pressure up") { auto vehicle{horn_vehicle(test::definition::load("wagon"))}; - vehicle->air.mainReservoirPressure = physics::Vehicle::HornMinPressure; + vehicle->air.SetPressureForTest(physics::Vehicle::HornMinPressure); CHECK(vehicle->SoundingHorns(horn::low) == horn::low); - vehicle->air.mainReservoirPressure = physics::Vehicle::HornMinPressure - 0.01; + vehicle->air.SetPressureForTest(physics::Vehicle::HornMinPressure - 0.01); CHECK(vehicle->SoundingHorns(horn::low) == 0); } diff --git a/tests/unit/test_line_contactors.cpp b/tests/unit/test_line_contactors.cpp index 4429189d6..f332b4432 100644 --- a/tests/unit/test_line_contactors.cpp +++ b/tests/unit/test_line_contactors.cpp @@ -10,7 +10,7 @@ namespace { test::vehicle locomotive(bool const Pressureswitch) { test::vehicle vehicle{test::definition::load("wagon").set("Engine", "PressureSwitch", Pressureswitch)}; vehicle->lineContactors.Open(); // the line contactors open - vehicle->brakePipe.pressure = 5.0; + vehicle->brakePipe.SetPressure(5.0); return vehicle; } diff --git a/tests/unit/test_line_contactors_interlock.cpp b/tests/unit/test_line_contactors_interlock.cpp index 567834712..74e59d392 100644 --- a/tests/unit/test_line_contactors_interlock.cpp +++ b/tests/unit/test_line_contactors_interlock.cpp @@ -24,7 +24,7 @@ vehicle ready(std::string_view const Interlock) { vehicle locomotive{loaded}; locomotive->lineBreaker.Close(); locomotive->DirActive = 1; - locomotive->brakePipe.pressure = 5.0; + locomotive->brakePipe.SetPressure(5.0); locomotive->brakes.cylinderPressure = 0.0; return locomotive; } @@ -133,7 +133,7 @@ bool close_line_contactors(test::driven const &Driven) { // the brakes released and the cylinders empty enough for the pressure switch to let the vehicle start void release(test::driven const &Driven) { test::release_brakes(Driven.cab); - for (int i = 0; i < 90 && (Driven.controlling.brakes.cylinderPressure > 0.1 || Driven.controlling.brakePipe.pressure < 4.8); ++i) { + for (int i = 0; i < 90 && (Driven.controlling.brakes.cylinderPressure > 0.1 || Driven.controlling.brakePipe.Pressure() < 4.8); ++i) { test::drive(Driven, line, 1.0); } } @@ -302,14 +302,14 @@ TEST_CASE("line contactors interlock: the ET42 section with its fans switched of TEST_CASE("louvres: closed until the main reservoir reaches the pressure that opens them") { vehicle et22{definition::fiz("et22_v3/201e-w")}; CHECK(et22->LouvresOpenPressure == doctest::Approx(5.0)); // by default - et22->air.mainReservoirPressure = 4.9; + et22->air.SetPressureForTest(4.9); CHECK(et22->LouvresClosed()); - et22->air.mainReservoirPressure = 5.0; + et22->air.SetPressureForTest(5.0); CHECK_FALSE(et22->LouvresClosed()); vehicle given{definition::fiz("et22_v3/201e-w").set("Cntrl", "LouvresOpenPressure", 4.0)}; - given->air.mainReservoirPressure = 4.5; + given->air.SetPressureForTest(4.5); CHECK_FALSE(given->LouvresClosed()); - given->air.mainReservoirPressure = 3.9; + given->air.SetPressureForTest(3.9); CHECK(given->LouvresClosed()); } diff --git a/tests/unit/test_mains_before_pantographs.cpp b/tests/unit/test_mains_before_pantographs.cpp index 309556072..ea615d1f5 100644 --- a/tests/unit/test_mains_before_pantographs.cpp +++ b/tests/unit/test_mains_before_pantographs.cpp @@ -57,9 +57,9 @@ void switch_auxiliaries_on(test::vehicle &Loco) { // what the main reservoir gains over the given time [bar]; the compressor of the locomotive adds some 0.07 bar a second double reservoir_gain(test::vehicle &Loco, double const Seconds, test::track const &Track) { - auto const before{Loco->air.compressedVolume}; + auto const before{Loco->air.CompressedVolume()}; Loco.run(Seconds, Track); - return (Loco->air.compressedVolume - before) / Loco->air.mainReservoirVolume; + return (Loco->air.CompressedVolume() - before) / Loco->air.config.mainReservoirVolume; } // the locomotive started up the way the driver does it, the brakes released, then the master controller taken to the @@ -168,7 +168,7 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres REQUIRE(loco->pantographCircuit.SupplyVoltage() == 0.0); switch_auxiliaries_on(loco); REQUIRE(loco->converter.IsAllowed()); - REQUIRE(loco->air.compressor.allow); + REQUIRE(loco->air.compressor.IsAllowed()); // the line breaker closed on the battery, the pantographs down: there's nothing to run them on CHECK(reservoir_gain(loco, 20.0, line) < 0.01); @@ -176,7 +176,7 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres CHECK_FALSE(loco->MainCircuitPowered()); CHECK_FALSE(loco->converter.IsRunning()); CHECK_FALSE(loco->lowVoltage.Is110vAvailable()); - CHECK_FALSE(loco->air.compressor.running); + CHECK_FALSE(loco->air.compressor.IsRunning()); // the pantograph up: the converter starts, and the compressor on its 110 V raise_pantograph(loco); @@ -185,7 +185,7 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres CHECK(loco->MainCircuitPowered()); CHECK(loco->converter.IsRunning()); CHECK(loco->lowVoltage.Is110vAvailable()); - CHECK(loco->air.compressor.running); + CHECK(loco->air.compressor.IsRunning()); // the voltage gone they stop, behind the line breaker which stays closed auto const *track{&line}; @@ -209,14 +209,14 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres CHECK_FALSE(loco->MainCircuitPowered()); CHECK_FALSE(loco->converter.IsRunning()); CHECK_FALSE(loco->lowVoltage.Is110vAvailable()); - CHECK_FALSE(loco->air.compressor.running); + CHECK_FALSE(loco->air.compressor.IsRunning()); } TEST_CASE("mains before pantographs: with the flag whatever else the main circuit feeds waits for the traction voltage too") { // a compressor on the main circuit rather than the converter's 110 V, the motor blowers, the blowers of the starting // resistors, the heating test::vehicle loco{ep05(true).set("Brake", "CompressorPower", "Main"), 0.0, "test", 1}; - REQUIRE(loco->air.compressor.supply == physics::CompressorSupply::mainCircuit); + REQUIRE(loco->air.compressor.config.supply == physics::CompressorSupply::mainCircuit); REQUIRE(loco->HeatingPowerSource.SourceType == TPowerSource::Main); prepare(loco); close_line_breaker(loco); @@ -228,7 +228,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui loco.hold_main_reservoir(-1.0); CHECK(reservoir_gain(loco, 10.0, line) < 0.01); - CHECK_FALSE(loco->air.compressor.running); + CHECK_FALSE(loco->air.compressor.IsRunning()); CHECK_FALSE(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot == 0.0); CHECK_FALSE(loco->trainHeating.IsOn()); @@ -238,7 +238,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui REQUIRE(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(weak.voltage)); CHECK(reservoir_gain(loco, 10.0, weak) < 0.01); CHECK(loco->lineBreaker.IsClosed()); - CHECK_FALSE(loco->air.compressor.running); + CHECK_FALSE(loco->air.compressor.IsRunning()); CHECK_FALSE(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot == 0.0); CHECK_FALSE(loco->trainHeating.IsOn()); @@ -247,7 +247,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui raise_pantograph(loco); REQUIRE(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); CHECK(reservoir_gain(loco, 10.0, line) > 0.1); - CHECK(loco->air.compressor.running); + CHECK(loco->air.compressor.IsRunning()); CHECK(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot > 0.0); CHECK(loco->trainHeating.IsOn()); @@ -265,14 +265,14 @@ TEST_CASE("mains before pantographs: without the flag the converter and the comp CHECK(loco->MainCircuitPowered()); CHECK(loco->converter.IsRunning()); CHECK(loco->lowVoltage.Is110vAvailable()); - CHECK(loco->air.compressor.running); + CHECK(loco->air.compressor.IsRunning()); // too low a voltage opens the line breaker, and they stop with it loco.run(5.0, weak); CHECK_FALSE(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->MainCircuitPowered()); CHECK_FALSE(loco->converter.IsRunning()); CHECK_FALSE(loco->lowVoltage.Is110vAvailable()); - CHECK_FALSE(loco->air.compressor.running); + CHECK_FALSE(loco->air.compressor.IsRunning()); } // the undervoltage trip was also what cut the traction motors off when the voltage went: the line contactors open diff --git a/tests/unit/test_pressure_switch.cpp b/tests/unit/test_pressure_switch.cpp index a45260b49..1fe1c76fb 100644 --- a/tests/unit/test_pressure_switch.cpp +++ b/tests/unit/test_pressure_switch.cpp @@ -74,13 +74,13 @@ void apply_independent_brake(test::vehicle &Loco, test::driven const &Driven) { Loco->IncLocalBrakeLevel(LocalBrakePosNo); test::drive(Driven, line, 20.0); REQUIRE(Loco->brakes.cylinderPressure == doctest::Approx(3.8).epsilon(0.03)); - REQUIRE(Loco->brakePipe.pressure > 4.8); + REQUIRE(Loco->brakePipe.Pressure() > 4.8); } void emergency_application(test::vehicle &Loco, test::driven const &Driven) { Loco->BrakeLevelSet(Loco->brakes.driverValve->GetPos(bh_EB)); test::drive(Driven, line, 10.0); - REQUIRE(Loco->brakePipe.pressure < 1.0); + REQUIRE(Loco->brakePipe.Pressure() < 1.0); } } // namespace @@ -138,8 +138,8 @@ TEST_CASE("pressure switch: without its brake cylinder half the brake pipe still SUBCASE("a service application") { loco->BrakeLevelSet(loco->brakes.driverValve->GetPos(bh_FB)); test::drive(driven, line, 15.0); - REQUIRE(loco->brakePipe.pressure < 3.6); - REQUIRE(loco->brakePipe.pressure > 3.0); + REQUIRE(loco->brakePipe.Pressure() < 3.6); + REQUIRE(loco->brakePipe.Pressure() > 3.0); } SUBCASE("an emergency application") { emergency_application(loco, driven); @@ -164,7 +164,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller loco->AlarmChainSwitch(true); } test::drive(driven, line, 10.0); - REQUIRE(loco->brakePipe.pressure < emergency_pressure); + REQUIRE(loco->brakePipe.Pressure() < emergency_pressure); REQUIRE(loco->MainCtrlPos == 5); CHECK_FALSE(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->pantographs[VehicleEnd::front].is_active); @@ -210,10 +210,10 @@ TEST_CASE("pressure switch: a service application with the master controller on // the last service position of the FV4a, 2.8 bar in the pipe loco->BrakeLevelSet(5.0); - auto lowest{loco->brakePipe.pressure}; + auto lowest{loco->brakePipe.Pressure()}; for (int second = 0; second < 60; ++second) { test::drive(driven, line, 1.0); - lowest = std::min(lowest, loco->brakePipe.pressure); + lowest = std::min(lowest, loco->brakePipe.Pressure()); } MESSAGE("the lowest brake pipe pressure of the service application: " << lowest << " bar"); REQUIRE(lowest < 3.0); @@ -273,7 +273,7 @@ TEST_CASE("pressure switch: after the emergency application the driver's start-u CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); - REQUIRE(loco->brakePipe.pressure < emergency_pressure); + REQUIRE(loco->brakePipe.Pressure() < emergency_pressure); // and it stays so test::drive(driven, line, 30.0); CHECK(loco->lineBreaker.IsClosed()); @@ -283,7 +283,7 @@ TEST_CASE("pressure switch: after the emergency application the driver's start-u // the pressure switch lets the start be made test::release_brakes(driven.cab); for (int i = 0; i < 180 && loco->protection.PressureSwitchTripped(); ++i) { - loco->BrakeReleaser(loco->brakePipe.pressure < 3.0 ? 1 : 0); + loco->BrakeReleaser(loco->brakePipe.Pressure() < 3.0 ? 1 : 0); test::drive(driven, line, 1.0); } loco->BrakeReleaser(0); diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp index d75fb2611..33f8bbfb5 100644 --- a/tests/unit/test_pullee.cpp +++ b/tests/unit/test_pullee.cpp @@ -43,7 +43,7 @@ struct hauled_train { void drain_feed_air(physics::Vehicle &Vehicle) { Vehicle.mainPipe.reservoir->CreatePress(0.0); Vehicle.mainPipe.reservoir->Act(); - Vehicle.air.compressedVolume = 0.0; + Vehicle.air.Fill(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 @@ -79,7 +79,7 @@ TEST_CASE("pullee: a dead Vectron vents the brake pipe of the train hauling it, REQUIRE_FALSE(train.hauled->PulleeMode); train.run(120.0); CHECK(train.hauled->brakes.emergencyValve.flow > 0.0); - CHECK(train.locomotive->brakePipe.pressure < 4.95); // the pipe sags although the locomotive keeps feeding it + CHECK(train.locomotive->brakePipe.Pressure() < 4.95); // the pipe sags although the locomotive keeps feeding it CHECK(train.hauled->brakes.cylinderPressure > 0.4); CHECK(train.hauled.speed() < 30.0); } @@ -87,7 +87,7 @@ TEST_CASE("pullee: a dead Vectron vents the brake pipe of the train hauling it, hauled_train train{vectron, 60.0, true}; train.run(120.0); CHECK(train.hauled->brakes.emergencyValve.flow == 0.0); - CHECK(train.locomotive->brakePipe.pressure > 4.99); + CHECK(train.locomotive->brakePipe.Pressure() > 4.99); CHECK(train.hauled->brakes.cylinderPressure < 0.1); CHECK(train.hauled->Fb < 1.0); CHECK(train.hauled.speed() > 40.0); // running resistance alone @@ -115,13 +115,13 @@ TEST_CASE("pullee: an EU07 with a driver can't release the brakes of a dead Vect if (false == pullee) { // the Vectron has emptied the brake pipe, and both locomotives stand on an emergency application CHECK(hauled->lowVoltage.IsBatteryOn()); - CHECK(locomotive->brakePipe.pressure < 1.0); + CHECK(locomotive->brakePipe.Pressure() < 1.0); CHECK(locomotive->brakes.cylinderPressure > 3.0); CHECK(hauled->brakes.cylinderPressure > 3.0); continue; } CHECK_FALSE(hauled->lowVoltage.IsBatteryOn()); - CHECK(locomotive->brakePipe.pressure > 4.9); + CHECK(locomotive->brakePipe.Pressure() > 4.9); CHECK(locomotive->brakes.cylinderPressure < 0.1); CHECK(hauled->brakes.cylinderPressure < 0.1); // the driver notches up watching the ammeter @@ -180,7 +180,7 @@ TEST_CASE("pullee: a dead EU47 starts to drag once its main reservoir has leaked CHECK(hauled.brakes.cylinderPressure < 0.1); CHECK(hauled.Fb < 1.0); train.run(1020.0); // 20 minutes since the start - CHECK(hauled.mainPipe.pressure < hauled.brakes.spring.minForcePressure); + CHECK(hauled.mainPipe.Pressure() < hauled.brakes.spring.minForcePressure); if (pullee) { CHECK(hauled.Fb < 1.0); } @@ -262,17 +262,17 @@ TEST_CASE("pullee: the brake valves in the cab of a vehicle prepared for hauling driven->DecLocalBrakeLevel(LocalBrakePosNo); driven.run(20.0); REQUIRE(driven->brakes.cylinderPressure < 0.1); - auto const charged{driven->brakePipe.pressure}; + auto const charged{driven->brakePipe.Pressure()}; // full service braking with the driver's valve driven->BrakeLevelSet(driven->brakes.driverValve->GetPos(bh_FB)); driven.run(10.0); if (pullee) { CHECK(driven->brakes.driverValveFlow == 0.0); - CHECK(driven->brakePipe.pressure > charged - 0.1); + CHECK(driven->brakePipe.Pressure() > charged - 0.1); CHECK(driven->brakes.cylinderPressure < 0.1); } else { - CHECK(driven->brakePipe.pressure < charged - 0.5); + CHECK(driven->brakePipe.Pressure() < charged - 0.5); CHECK(driven->brakes.cylinderPressure > 1.0); } // and the emergency position @@ -280,10 +280,10 @@ TEST_CASE("pullee: the brake valves in the cab of a vehicle prepared for hauling driven.run(10.0); if (pullee) { CHECK(driven->brakes.driverValveFlow == 0.0); - CHECK(driven->brakePipe.pressure > charged - 0.1); + CHECK(driven->brakePipe.Pressure() > charged - 0.1); } else { - CHECK(driven->brakePipe.pressure < 1.0); + CHECK(driven->brakePipe.Pressure() < 1.0); } } } @@ -421,7 +421,7 @@ TEST_CASE("pullee: every real vehicle prepared for hauling runs free behind a lo CHECK(hauled.brakes.emergencyValve.flow == 0.0); CHECK(hauled.brakes.cylinderPressure < 0.1); CHECK(hauled.Fb < 1.0); - CHECK(train.locomotive->brakePipe.pressure > 4.99); + CHECK(train.locomotive->brakePipe.Pressure() > 4.99); CHECK(train.hauled.speed() > 40.0); } } diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index 88e7a3b99..b9d678436 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -161,7 +161,7 @@ void vehicle::step(track const &Track, double Dt) { fast_move(Track, Dt, location); } forces(Dt); - move(Track, Dt, location, m_physics->brakePipe.pressure); + move(Track, Dt, location, m_physics->brakePipe.Pressure()); } namespace { @@ -204,8 +204,8 @@ void vehicle::begin_step() { if (m_pipepressure >= 0.0) { m_physics->brakePipe.reservoir->CreatePress(m_pipepressure); } - if (m_reservoirpressure >= 0.0 && m_physics->air.mainReservoirVolume > 0.0) { - m_physics->air.compressedVolume = m_reservoirpressure * m_physics->air.mainReservoirVolume; + if (m_reservoirpressure >= 0.0 && m_physics->air.config.mainReservoirVolume > 0.0) { + m_physics->air.Fill(m_reservoirpressure * m_physics->air.config.mainReservoirVolume); } // vehicle_table::update(), before the forces m_physics->ComputeConstans(); @@ -335,7 +335,7 @@ void pair::step(track const &Track, double Dt) { } for (auto &placed : m_vehicles) { auto const &physics{placed.owner->physics()}; - placed.position += placed.heading * placed.owner->move(Track, Dt, TLocation{placed.position, 0.0, 0.0}, physics.brakePipe.pressure); + placed.position += placed.heading * placed.owner->move(Track, Dt, TLocation{placed.position, 0.0, 0.0}, physics.brakePipe.Pressure()); } // vehicle_table::update_brake_pipes() physics::Vehicle::UpdatePipeCouplers({&m_vehicles[0].owner->physics(), &m_vehicles[1].owner->physics()}, Dt); diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index ca3fb0934..b5cd7e78a 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -107,7 +107,7 @@ void TController::Activation() if( occupied->brakes.handlePositions > 0 && ( BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic ) ) { - occupied->brakes.pipeLimiterPressure = occupied->brakePipe.pressure; + occupied->brakes.pipeLimiterPressure = occupied->brakePipe.Pressure(); occupied->ActFlowSpeed = 0; } BrakeLevelSet( occupied->brakes.handlePosition ); @@ -703,7 +703,7 @@ TController::determine_consist_state() { Ready = true; // wstępnie gotowy fReady = 0.0; // założenie, że odhamowany IsConsistBraked = occupied->brakes.kind == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ? occupied->brakes.cylinderPressure > 2.0 : - occupied->brakePipe.pressure < std::max(3.9, occupied->brakes.actualPressure.PipePressureVal) + 0.1; + occupied->brakePipe.Pressure() < std::max(3.9, occupied->brakes.actualPressure.PipePressureVal) + 0.1; fAccGravity = 0.0; // przyspieszenie wynikające z pochylenia IsAnyCouplerStretched = false; IsAnyDoorOnlyOpen[ VehicleSide::right ] = IsAnyDoorOnlyOpen[ VehicleSide::left ] = false; @@ -729,7 +729,7 @@ TController::determine_consist_state() { if( ( vehicle->brakes.kind != TBrakeSystem::Individual ) && ( vehicle->brakes.maxCylinderPressure[ 3 ] > 0.0 ) && ( false == TestFlag( vehicle->brakes.distributor->GetBrakeStatus(), b_dmg ) ) ) { // a brake cut out doesn't count - chargelevel = std::min( { chargelevel, vehicle->brakePipe.pressure, vehicle->brakes.distributor->GetBRP() } ); + chargelevel = std::min( { chargelevel, vehicle->brakePipe.Pressure(), vehicle->brakes.distributor->GetBRP() } ); } auto const wasready { Ready }; if( released || Ready ) { @@ -751,14 +751,14 @@ TController::determine_consist_state() { // Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka... if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && occupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy && false == TestFlag(vehicle->brakes.distributor->GetBrakeStatus(), b_dmg) // brake isn't broken - && vehicle->brakePipe.pressure - occupied->brakes.driverValve->GetRP() > -0.1 // jeśli ciśnienie jak dla jazdy - && vehicle->brakes.distributor->GetCRP() > vehicle->brakePipe.pressure + 0.12 ) { // wg UIC określone sztywno na 0.04 + && vehicle->brakePipe.Pressure() - occupied->brakes.driverValve->GetRP() > -0.1 // jeśli ciśnienie jak dla jazdy + && vehicle->brakes.distributor->GetCRP() > vehicle->brakePipe.Pressure() + 0.12 ) { // wg UIC określone sztywno na 0.04 // za dużo w zbiorniku // indywidualne luzowanko vehicle->BrakeReleaser(1); } if (bp < 0.1 && (AIControllFlag || Global.AITrainman) && false == TestFlag(vehicle->brakes.distributor->GetBrakeStatus(), b_dmg) // brake isn't broken - && vehicle->brakes.distributor->GetCRP() < vehicle->brakePipe.pressure - 0.1) { + && vehicle->brakes.distributor->GetCRP() < vehicle->brakePipe.Pressure() - 0.1) { // już nie jest za dużo w zbiorniku // koniec indywidualnego luzowanka vehicle->BrakeReleaser(0); @@ -826,9 +826,9 @@ TController::determine_consist_state() { IsAnyConverterOverloadRelayOpen |= vehicle->converter.IsOverloaded(); IsAnyMotorOverloadRelayOpen |= vehicle->FuseFlag; IsAnyGroundRelayOpen |= !vehicle->protection.GroundHolds(); - IsAnyCompressorPresent |= vehicle->air.compressor.speed > 0.0; - IsAnyCompressorEnabled |= vehicle->air.compressor.speed > 0.0 ? (vehicle->air.compressor.allow || vehicle->air.compressor.start == start_t::automatic) && vehicle->air.compressor.allowLocal : false; - IsAnyCompressorExplicitlyEnabled |= vehicle->air.compressor.speed > 0.0 ? vehicle->air.compressor.allow && vehicle->air.compressor.allowLocal : false; + IsAnyCompressorPresent |= vehicle->air.compressor.config.speed > 0.0; + IsAnyCompressorEnabled |= vehicle->air.compressor.config.speed > 0.0 ? (vehicle->air.compressor.IsAllowed() || vehicle->air.compressor.config.start == start_t::automatic) && vehicle->air.compressor.LocalSwitchOn() : false; + IsAnyCompressorExplicitlyEnabled |= vehicle->air.compressor.config.speed > 0.0 ? vehicle->air.compressor.IsAllowed() && vehicle->air.compressor.LocalSwitchOn() : false; IsAnyConverterPresent |= vehicle->converter.config.start != start_t::disabled; IsAnyConverterEnabled |= ( vehicle->converter.IsAllowed() || vehicle->converter.config.start == start_t::automatic ) && vehicle->converter.LocalSwitchOn(); IsAnyConverterExplicitlyEnabled |= vehicle->converter.IsAllowed() && vehicle->converter.LocalSwitchOn(); @@ -898,15 +898,15 @@ TController::determine_consist_state() { // a human driver's handle, which BrakeCtrlPosition doesn't follow occupied->brakes.handlePositionSmooth > occupied->brakes.driverValve->GetPos( bh_RP ) + 0.2 }; auto const reference { - brake_charge::reference( occupied->brakePipe.pressure, std::min( occupied->brakes.driverValve->GetRP(), 5.0 ), trainbrakeapplied ) }; + brake_charge::reference( occupied->brakePipe.Pressure(), std::min( occupied->brakes.driverValve->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->air.mainReservoirPressure, occupied->air.mainReservoirPressure ) > reference ) - && ( occupied->brakePipe.pressure >= reference - brake_charge::margin ) }; + && ( std::max( mvControlling->air.MainReservoirPressure(), occupied->air.MainReservoirPressure() ) > reference ) + && ( occupied->brakePipe.Pressure() >= reference - brake_charge::margin ) }; auto const wasstalled { BrakeCharge.stalled }; IsConsistCharged = brake_charge::charged( BrakeCharge, chargelevel, reference, ElapsedTime, supplied ); if( BrakeCharge.stalled && ( false == wasstalled ) ) { diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index e665c6248..5233b6743 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -116,7 +116,7 @@ bool TController::PrepareEngine() else { // jeżeli jest wystarczające ciśnienie w pantografach if( false == pantographUnit->pantographAir.IsConnectedToMainReservoir() - || pantographUnit->pantographAir.Pressure() <= pantographUnit->mainPipe.pressure ) { // kurek przełączony albo główna już pompuje + || pantographUnit->pantographAir.Pressure() <= pantographUnit->mainPipe.Pressure() ) { // kurek przełączony albo główna już pompuje cue_action( driver_hint::pantographcompressoroff ); // sprężarkę pantografów można już wyłączyć } } @@ -163,7 +163,7 @@ bool TController::PrepareEngine() if( IsAnyCompressorPresent && IsAnyConverterEnabled ) { cue_action( driver_hint::compressoron ); } - if( mvControlling->mainPipe.pressure < 4.5 && mvControlling->air.mainReservoirVolume > 0.0 ) { + if( mvControlling->mainPipe.Pressure() < 4.5 && mvControlling->air.config.mainReservoirVolume > 0.0 ) { cue_action( driver_hint::waitpressuretoolow ); } // enable motor blowers @@ -207,7 +207,7 @@ bool TController::PrepareEngine() && false == IsAnyLineBreakerOpen && ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled ) && ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled ) - && ( mvControlling->mainPipe.pressure > 4.5 || mvControlling->air.mainReservoirVolume == 0.0 ); + && ( mvControlling->mainPipe.Pressure() > 4.5 || mvControlling->air.config.mainReservoirVolume == 0.0 ); } if( true == isready ) { diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp index 69967d99e..b8cc3c823 100644 --- a/vehicle/ai/force.cpp +++ b/vehicle/ai/force.cpp @@ -603,7 +603,7 @@ void TController::control_releaser() { brake_releaser::conditions state; state.acceleration_desired = AccDesired; - state.pipe_pressure = occupied->brakePipe.pressure; + state.pipe_pressure = occupied->brakePipe.Pressure(); state.cylinder_pressure = occupied->brakes.cylinderPressure; state.control_pressure = occupied->brakes.distributor->GetCRP(); state.velocity = occupied->Vel; @@ -671,7 +671,7 @@ void TController::control_main_pipe() { auto const departblocked { is_departure_blocked( DepartBlockedFSDelay ) }; if( (drivingFlags.oerlikons || true == IsCargoTrain || departblocked) && BrakeCtrlPosition == gbh_RP && AbsAccS < 0.03 && AccDesired > -0.03 && VelDesired - occupied->Vel > 2.0 && fReady > 0.35 && ( occupied->brakes.equivalentPipePressure < 4.5 || departblocked ) // don't charge with a risk of overcharging the main pipe - && occupied->air.mainReservoirPressure >= 7.5 // don't charge without sufficient pressure in the tank + && occupied->air.MainReservoirPressure() >= 7.5 // don't charge without sufficient pressure in the tank && BrakeChargingCooldown >= 0.0 // don't charge while cooldown is active && (ActualProximityDist > 100.0 // don't charge if we're about to be braking soon || min_speed(occupied->Vel, VelNext) >= occupied->Vel) ) { @@ -683,7 +683,7 @@ void TController::control_main_pipe() { update_brake_charging(); - if( ( occupied->air.mainReservoirPressure < 5.0 + if( ( occupied->air.MainReservoirPressure() < 5.0 || ( BrakeCtrlPosition < gbh_RP && ( occupied->brakes.equivalentPipePressure > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) // the light application a charging train stands on stays, as in DecBrake() @@ -707,7 +707,7 @@ void TController::update_brake_charging() { for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { auto const isovercharged { vehicle->physics != occupied - && vehicle->physics->brakePipe.pressure > FSOverchargePipePress }; + && vehicle->physics->brakePipe.Pressure() > FSOverchargePipePress }; if( isovercharged ) { BrakeChargingPipeOverchargeStart.try_emplace( vehicle, ElapsedTime ); } diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp index 820c90e9a..8430beac7 100644 --- a/vehicle/ai/physicslog.cpp +++ b/vehicle/ai/physicslog.cpp @@ -73,7 +73,7 @@ std::string TController::physicslog_line() const { << occupied->Ff << " " << occupied->Fb << " " << occupied->brakes.cylinderPressure << " " - << occupied->brakePipe.pressure << " " + << occupied->brakePipe.Pressure() << " " << mvControlling->Im << " " << int(mvControlling->MainCtrlPos) << " " << int(mvControlling->ScndCtrlPos) << " " @@ -117,7 +117,7 @@ void TController::PhysicsLog() line << ElapsedTime << "\t" << fabs(11.31 * occupied->WheelDiameter * occupied->nrot) << "\t"; line << mvControlling->AccS << "\t"; - line << occupied->brakePipe.pressure << "\t" << occupied->brakes.controlReservoirPressure << "\t" + line << occupied->brakePipe.Pressure() << "\t" << occupied->brakes.controlReservoirPressure << "\t" << occupied->brakes.cylinderPressure << "\t"; line << occupied->brakes.reservoirAir << "\t" << occupied->brakes.distributor->GetCRP() << "\n"; PhysicsLogs.append( VehicleName, line.str() ); diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index 755e24f7a..d51431ecc 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -143,7 +143,7 @@ TController::control_pantographs() { if( pantographUnit->EnginePowerSource.SourceType != TPowerSource::CurrentCollector ) { return; } if( false == pantographUnit->pantographAir.config.autoValve - && occupied->mainPipe.pressure > 4.3 ) { + && occupied->mainPipe.Pressure() > 4.3 ) { // gdy główna sprężarka bezpiecznie nabije ciśnienie to można przestawić kurek na zasilanie pantografów z głównej pneumatyki cue_action( driver_hint::pantographairsourcesetmain ); } diff --git a/vehicle/cab/auxiliarycommands.cpp b/vehicle/cab/auxiliarycommands.cpp index 268e974b2..a815257f4 100644 --- a/vehicle/cab/auxiliarycommands.cpp +++ b/vehicle/cab/auxiliarycommands.cpp @@ -843,7 +843,7 @@ void TTrain::OnCommand_compressortoggle(TTrain *Train, command_data const &Comma if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const compressorisenabled{(Train->Dynamic()->Mechanik ? Train->Dynamic()->Mechanik->IsAnyCompressorEnabled : Train->occupied->air.compressor.allow)}; + auto const compressorisenabled{(Train->Dynamic()->Mechanik ? Train->Dynamic()->Mechanik->IsAnyCompressorEnabled : Train->occupied->air.compressor.IsAllowed())}; if (false == compressorisenabled) { @@ -895,7 +895,7 @@ void TTrain::OnCommand_compressorenable(TTrain *Train, command_data const &Comma void TTrain::OnCommand_compressordisable(TTrain *Train, command_data const &Command) { - if (Train->controlled->air.compressor.supply >= physics::CompressorSupply::converter) + if (Train->controlled->air.compressor.config.supply >= physics::CompressorSupply::converter) { return; } @@ -921,7 +921,7 @@ void TTrain::OnCommand_compressordisable(TTrain *Train, command_data const &Comm void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const &Command) { - if (Train->occupied->air.compressor.supply >= physics::CompressorSupply::converter) + if (Train->occupied->air.compressor.config.supply >= physics::CompressorSupply::converter) { return; } @@ -933,13 +933,13 @@ void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const & if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->occupied->air.compressor.allowLocal) + if (false == Train->occupied->air.compressor.LocalSwitchOn()) { // turn on // visual feedback Train->ggCompressorLocalButton.UpdateValue(1.0, Train->dsbSwitch); // effect - Train->occupied->air.compressor.allowLocal = true; + Train->occupied->air.compressor.SetLocalSwitch(true); } else { @@ -947,7 +947,7 @@ void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const & // visual feedback Train->ggCompressorLocalButton.UpdateValue(0.0, Train->dsbSwitch); // effect - Train->occupied->air.compressor.allowLocal = false; + Train->occupied->air.compressor.SetLocalSwitch(false); } } } @@ -955,7 +955,7 @@ void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const & void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data const &Command) { - if (Train->occupied->air.compressor.listPositions == 0) + if (Train->occupied->air.compressor.config.listPositions == 0) { return; } @@ -967,14 +967,14 @@ void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data if (Train->ggCompressorListButton.type() == TGaugeType::push) { // impulse switch - if (Train->occupied->air.compressor.listPositions < Train->occupied->air.compressor.listDefaultPosition + 1) + if (Train->occupied->air.compressor.config.listPositions < Train->occupied->air.compressor.config.listDefaultPosition + 1) { return; } - Train->occupied->ChangeCompressorPreset(Command.action == GLFW_PRESS ? Train->occupied->air.compressor.listDefaultPosition + 1 : Train->occupied->air.compressor.listDefaultPosition); + Train->occupied->ChangeCompressorPreset(Command.action == GLFW_PRESS ? Train->occupied->air.compressor.config.listDefaultPosition + 1 : Train->occupied->air.compressor.config.listDefaultPosition); // visual feedback - Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.listPosition - 1), Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.ListPosition() - 1), Train->dsbSwitch); } else { @@ -984,12 +984,12 @@ void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data return; } - if (Train->occupied->air.compressor.listPosition < Train->occupied->air.compressor.listPositions || true == Train->occupied->air.compressor.listWraps) + if (Train->occupied->air.compressor.ListPosition() < Train->occupied->air.compressor.config.listPositions || true == Train->occupied->air.compressor.config.listWraps) { // active light preset is stored as value in range 1-LigthPosNo - Train->occupied->ChangeCompressorPreset(Train->occupied->air.compressor.listPosition < Train->occupied->air.compressor.listPositions ? Train->occupied->air.compressor.listPosition + 1 : 1); // wrap mode + Train->occupied->ChangeCompressorPreset(Train->occupied->air.compressor.ListPosition() < Train->occupied->air.compressor.config.listPositions ? Train->occupied->air.compressor.ListPosition() + 1 : 1); // wrap mode // visual feedback - Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.listPosition - 1), Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.ListPosition() - 1), Train->dsbSwitch); } } } @@ -997,7 +997,7 @@ void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data void TTrain::OnCommand_compressorpresetactivateprevious(TTrain *Train, command_data const &Command) { - if (Train->occupied->air.compressor.listPositions == 0) + if (Train->occupied->air.compressor.config.listPositions == 0) { return; } @@ -1012,15 +1012,15 @@ void TTrain::OnCommand_compressorpresetactivateprevious(TTrain *Train, command_d return; } - if (Train->occupied->air.compressor.listPosition > 1 || true == Train->occupied->air.compressor.listWraps) + if (Train->occupied->air.compressor.ListPosition() > 1 || true == Train->occupied->air.compressor.config.listWraps) { // active light preset is stored as value in range 1-LigthPosNo - Train->occupied->ChangeCompressorPreset(Train->occupied->air.compressor.listPosition > 1 ? Train->occupied->air.compressor.listPosition - 1 : Train->occupied->air.compressor.listPositions); // wrap mode + Train->occupied->ChangeCompressorPreset(Train->occupied->air.compressor.ListPosition() > 1 ? Train->occupied->air.compressor.ListPosition() - 1 : Train->occupied->air.compressor.config.listPositions); // wrap mode // visual feedback if (Train->ggCompressorListButton.SubModel != nullptr) { - Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.listPosition - 1), Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.ListPosition() - 1), Train->dsbSwitch); } } } @@ -1028,7 +1028,7 @@ void TTrain::OnCommand_compressorpresetactivateprevious(TTrain *Train, command_d void TTrain::OnCommand_compressorpresetactivatedefault(TTrain *Train, command_data const &Command) { - if (Train->occupied->air.compressor.listPositions == 0) + if (Train->occupied->air.compressor.config.listPositions == 0) { return; } @@ -1037,12 +1037,12 @@ void TTrain::OnCommand_compressorpresetactivatedefault(TTrain *Train, command_da return; } // one change per key press - Train->occupied->ChangeCompressorPreset(Train->occupied->air.compressor.listDefaultPosition); + Train->occupied->ChangeCompressorPreset(Train->occupied->air.compressor.config.listDefaultPosition); // visual feedback if (Train->ggCompressorListButton.SubModel != nullptr) { - Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.listPosition - 1), Train->dsbSwitch); + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.ListPosition() - 1), Train->dsbSwitch); } } diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index c1cef46ad..bc7847051 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -995,9 +995,9 @@ void TTrain::set_cab_controls(int const Cab) } ggConverterLocalButton.PutValue(occupied->converter.LocalSwitchOn() ? 1.f : 0.f); // compressor - ggCompressorButton.PutValue(controlled->air.compressor.allow ? 1.f : 0.f); - ggCompressorLocalButton.PutValue(controlled->air.compressor.allowLocal ? 1.f : 0.f); - ggCompressorListButton.PutValue(static_cast(occupied->air.compressor.listPosition - 1)); + ggCompressorButton.PutValue(controlled->air.compressor.IsAllowed() ? 1.f : 0.f); + ggCompressorLocalButton.PutValue(controlled->air.compressor.LocalSwitchOn() ? 1.f : 0.f); + ggCompressorListButton.PutValue(static_cast(occupied->air.compressor.ListPosition() - 1)); // motor overload relay threshold / shunt mode ggMaxCurrentCtrl.PutValue(true == controlled->ShuntModeAllow ? (true == controlled->ShuntMode ? 1.f : 0.f) : controlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); // automatic relays (AutoRelay) @@ -1824,14 +1824,14 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // manometr przewodu hamulcowego auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&occupied->brakePipe.pressure); + gauge.AssignDouble(&occupied->brakePipe.Pressure()); } else if (Label == "scndpress:") { // manometr przewodu hamulcowego auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&occupied->mainPipe.pressure); + gauge.AssignDouble(&occupied->mainPipe.Pressure()); } else if (Label == "limpipepress:") { @@ -1866,7 +1866,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // manometr sprezarki/zbiornika glownego auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&occupied->air.mainReservoirPressure); + gauge.AssignDouble(&occupied->air.MainReservoirPressure()); } else if (Label == "oilpress:") { diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 2ea772fb8..7c7546b0a 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -179,7 +179,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("main_ready", false == controlled->lineBreaker.IsClosed() && fHVoltage > 0.0 && controlled->lineBreaker.IsInitialised()); dict->insert("converter", occupied->lowVoltage.Is110vAvailable()); dict->insert("converter_overload", controlled->converter.IsOverloaded()); - dict->insert("compress", controlled->air.compressor.running); + dict->insert("compress", controlled->air.compressor.IsRunning()); dict->insert("pant_compressor", pantographUnit->pantographAir.IsCompressorRunning()); dict->insert("lights_front", occupied->iLights[VehicleEnd::front]); dict->insert("lights_rear", occupied->iLights[VehicleEnd::rear]); @@ -411,8 +411,8 @@ TTrain::state_t TTrain::get_state() const occupied->SecuritySystem.is_beeping(), btLampkaHVoltageB.GetValue(), fTachoVelocity, - static_cast(occupied->air.mainReservoirPressure), - static_cast(occupied->brakePipe.pressure), + static_cast(occupied->air.MainReservoirPressure()), + static_cast(occupied->brakePipe.Pressure()), static_cast(occupied->brakes.cylinderPressure), static_cast(pantographUnit->pantographAir.Pressure()), fHVoltage, @@ -677,7 +677,7 @@ void TTrain::MoveToVehicle(TDynamicObject *target) if (Dynamic()->Mechanik) Dynamic()->Mechanik->MoveTo(target); - target_train->Occupied()->brakes.pipeLimiterPressure = target_train->Occupied()->brakePipe.pressure; + target_train->Occupied()->brakes.pipeLimiterPressure = target_train->Occupied()->brakePipe.Pressure(); target_train->Occupied()->CabActivisationAuto(true); // załączenie rozrządu (wirtualne kabiny) target_train->Dynamic()->MechInside = true; if (target_train->Dynamic()->Mechanik) @@ -748,7 +748,7 @@ void TTrain::MoveToVehicle(TDynamicObject *target) Dynamic()->Controller = Humandriver; } - Occupied()->brakes.pipeLimiterPressure = Occupied()->brakePipe.pressure; + Occupied()->brakes.pipeLimiterPressure = Occupied()->brakePipe.Pressure(); Occupied()->CabActivisationAuto(true); // załączenie rozrządu (wirtualne kabiny) } else diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 34bb1a9df..9aaba532c 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -433,8 +433,8 @@ void TTrain::updateUnitStates() if (p) { fPress[i][0] = static_cast(p->physics->brakes.cylinderPressure); - fPress[i][1] = static_cast(p->physics->brakePipe.pressure); - fPress[i][2] = static_cast(p->physics->mainPipe.pressure); + fPress[i][1] = static_cast(p->physics->brakePipe.Pressure()); + fPress[i][2] = static_cast(p->physics->mainPipe.Pressure()); fPress[i][3] = static_cast(p->physics->brakes.controlReservoirPressure); fPress[i][4] = static_cast(p->physics->brakes.distributor->GetBRP()); fPress[i][5] = static_cast((p->physics->TotalMass - p->physics->Mred) * 0.001); @@ -458,15 +458,15 @@ void TTrain::updateUnitStates() // TBD, TODO: clean up compressor data arrangement? if (iUnitNo <= 8) { - bComp[iUnitNo - 1][0] = bComp[iUnitNo - 1][0] || p->physics->air.compressor.allow || p->physics->air.compressor.start == start_t::automatic; + bComp[iUnitNo - 1][0] = bComp[iUnitNo - 1][0] || p->physics->air.compressor.IsAllowed() || p->physics->air.compressor.config.start == start_t::automatic; } - if (p->physics->air.compressor.speed > 0.00001) + if (p->physics->air.compressor.config.speed > 0.00001) { if (iUnitNo <= 8) { - bComp[iUnitNo - 1][1] = bComp[iUnitNo - 1][1] || p->physics->air.compressor.running; + bComp[iUnitNo - 1][1] = bComp[iUnitNo - 1][1] || p->physics->air.compressor.IsRunning(); } - bCompressors.emplace_back(p->physics->air.compressor.allow || p->physics->air.compressor.start == start_t::automatic, p->physics->air.compressor.running, i); + bCompressors.emplace_back(p->physics->air.compressor.IsAllowed() || p->physics->air.compressor.config.start == start_t::automatic, p->physics->air.compressor.IsRunning(), i); } bSlip[i] = p->physics->SlippingWheels; if (in < 8 && p->physics->inductionMotor.traction.maxPower > 1) @@ -581,9 +581,9 @@ void TTrain::updateFeedbackGauges() const { // wykonywać tylko gdy wyprowadzone na pulpit // Ra: sterowanie miernikiem: zbiornik główny - Console::ValueSet(0, occupied->air.mainReservoirPressure); + Console::ValueSet(0, occupied->air.MainReservoirPressure()); // Ra: sterowanie miernikiem: przewód główny - Console::ValueSet(1, occupied->brakePipe.pressure); + Console::ValueSet(1, occupied->brakePipe.Pressure()); // Ra: sterowanie miernikiem: cylinder hamulcowy Console::ValueSet(2, occupied->brakes.cylinderPressure); // woltomierz wysokiego napięcia @@ -607,7 +607,7 @@ void TTrain::updateConverterOverload(double const Deltatime) if (controlled->converter.IsRunning() == true) { fConverterTimer += static_cast(Deltatime); - if (controlled->air.compressor.running == true && controlled->air.compressor.supply == physics::CompressorSupply::converterManual && (controlled->EngineType == TEngineType::ElectricSeriesMotor || controlled->TrainType == train_type::emu) && + if (controlled->air.compressor.IsRunning() == true && controlled->air.compressor.config.supply == physics::CompressorSupply::converterManual && (controlled->EngineType == TEngineType::ElectricSeriesMotor || controlled->TrainType == train_type::emu) && DynamicObject->Controller == Humandriver // hunter-110212: poprawka dla EZT && DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag) { // hunter-091012: poprawka (zmiana warunku z CompressorPower /rozne od 0/ na /rowne 1/) @@ -620,7 +620,7 @@ void TTrain::updateConverterOverload(double const Deltatime) else if (fConverterTimer >= fConverterPrzekaznik) { // changed switch from always true to take into account state of the compressor switch - controlled->CompressorSwitch(controlled->air.compressor.allow); + controlled->CompressorSwitch(controlled->air.compressor.IsAllowed()); } } } @@ -777,7 +777,7 @@ void TTrain::updateBasicLamps() } // Lampka pracujacej sprezacki - if (controlled->air.compressor.running || occupied->air.compressor.running) + if (controlled->air.compressor.IsRunning() || occupied->air.compressor.IsRunning()) btCompressors.Turn(true); else btCompressors.Turn(false); @@ -848,8 +848,8 @@ void TTrain::updateCircuitLamps(double const Deltatime) btLampkaWysRozr.Turn(controlled->Imax >= controlled->ImaxHi); btLampkaNapNastHam.Turn(controlled->DirActive != 0); // napiecie na nastawniku hamulcowym - btLampkaSprezarka.Turn(controlled->air.compressor.running); // mutopsitka dziala - btLampkaSprezarkaOff.Turn(!controlled->air.compressor.running); + btLampkaSprezarka.Turn(controlled->air.compressor.IsRunning()); // mutopsitka dziala + btLampkaSprezarkaOff.Turn(!controlled->air.compressor.IsRunning()); btLampkaFuelPumpOff.Turn(!controlled->FuelPump.is_active); btLampkaOilPump.Turn(controlled->OilPump.is_active); // pre-lubrication pump, goes off once the engine is started @@ -1125,8 +1125,8 @@ void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) } } - btLampkaSprezarkaB.Turn(physics->air.compressor.running); // mutopsitka dziala - btLampkaSprezarkaBOff.Turn(false == physics->air.compressor.running); + btLampkaSprezarkaB.Turn(physics->air.compressor.IsRunning()); // mutopsitka dziala + btLampkaSprezarkaBOff.Turn(false == physics->air.compressor.IsRunning()); if (controlled->Signalling == true) { if (physics->brakes.cylinderPressure >= 1.45f) diff --git a/vehicle/dynamic/consist.cpp b/vehicle/dynamic/consist.cpp index 22d3c1a92..f5141d3be 100644 --- a/vehicle/dynamic/consist.cpp +++ b/vehicle/dynamic/consist.cpp @@ -109,7 +109,7 @@ float TDynamicObject::GetEPP() { if (!temp) break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów - eq += temp->physics->brakePipe.pressure * temp->physics->Dim.L; + eq += temp->physics->brakePipe.Pressure() * temp->physics->Dim.L; am += temp->physics->Dim.L; if ((temp->physics->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) break; // nic nie ma już dalej podłączone @@ -143,7 +143,7 @@ float TDynamicObject::GetEPP() { if (!temp) break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów - eq += temp->physics->brakePipe.pressure * temp->physics->Dim.L; + eq += temp->physics->brakePipe.Pressure() * temp->physics->Dim.L; am += temp->physics->Dim.L; if ((temp->physics->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) break; // nic nie ma już dalej podłączone @@ -170,7 +170,7 @@ float TDynamicObject::GetEPP() break; // jeśli jednak z tyłu nic nie ma } } - eq -= physics->brakePipe.pressure * physics->Dim.L; + eq -= physics->brakePipe.Pressure() * physics->Dim.L; am -= physics->Dim.L; return eq / am; }; diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index b3c7ed654..f9fac57ff 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -351,11 +351,11 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" { physics->brakes.distributor->ForceEmptiness(); physics->brakePipe.reservoir->CreatePress(0.0); - physics->brakePipe.pressure = 0.0; + physics->brakePipe.SetPressure(0.0); physics->mainPipe.reservoir->CreatePress(0.0); - physics->mainPipe.pressure = 0.0; + physics->mainPipe.SetPressure(0.0); physics->pantographAir.Empty(); - physics->air.compressedVolume = 0.0; + physics->air.Fill(0.0); } if ( contains( ActPar, '1' ) ) // wylaczanie 10% diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index 31ea07e97..4eca3f008 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -150,11 +150,11 @@ void TDynamicObject::renderAuxiliarySounds() { - if( physics->air.compressor.speed > 0.0 ) { + if( physics->air.compressor.config.speed > 0.0 ) { // McZapkie! - dzwiek compressor.wav tylko gdy dziala sprezarka - if( physics->air.compressor.running ) { + if( physics->air.compressor.IsRunning() ) { // for compressor coupled with the diesel engine sound pitch is driven by engine revolutions - if( physics->air.compressor.supply == physics::CompressorSupply::engine ) { + if( physics->air.compressor.config.supply == physics::CompressorSupply::engine ) { // presume the compressor sound is recorded for idle revolutions // increase the pitch according to increase of engine revolutions auto const enginefactor { @@ -170,7 +170,7 @@ void TDynamicObject::renderAuxiliarySounds() { } else { // enhanced sound path, with dedicated sound for idling compressor - if( physics->air.compressor.governorLock ) { + if( physics->air.compressor.IsGovernorLocked() ) { sCompressor.stop(); sCompressorIdle.play( sound_flags::exclusive | sound_flags::looping ); } @@ -308,7 +308,7 @@ void TDynamicObject::renderEmergencyBrakeSound() { // smooth out air flow rate m_emergencybrakeflow = m_emergencybrakeflow == 0.0 ? physics->brakes.emergencyValve.flow : std::lerp(m_emergencybrakeflow, physics->brakes.emergencyValve.flow, 0.1); // scale volume based on the flow rate and on the pressure in the main pipe - auto const flowpressure { std::clamp( m_emergencybrakeflow, 0.0, 1.0 ) + std::clamp( 0.1 * physics->brakePipe.pressure, 0.0, 0.5 ) }; + auto const flowpressure { std::clamp( m_emergencybrakeflow, 0.0, 1.0 ) + std::clamp( 0.1 * physics->brakePipe.Pressure(), 0.0, 0.5 ) }; m_emergencybrake .pitch( m_emergencybrake.m_frequencyoffset + 1.0 * m_emergencybrake.m_frequencyfactor ) .gain( m_emergencybrake.m_amplitudeoffset + std::clamp( flowpressure, 0.0, 1.0 ) * m_emergencybrake.m_amplitudefactor ) diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 1b65057ff..ffff2a58a 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -1530,20 +1530,7 @@ void TDynamicObject::Damage(char flag) { } - if (flag & 8) //blokada sprezarki - { - if (physics->air.compressor.minPressure>0) - physics->air.compressor.minPressure -= 100000001; - if (physics->air.compressor.maxPressure>0) - physics->air.compressor.maxPressure -= 100000001; - } - else - { - if (physics->air.compressor.minPressure<0) - physics->air.compressor.minPressure += 100000001; - if (physics->air.compressor.maxPressure<0) - physics->air.compressor.maxPressure += 100000001; - } + physics->air.compressor.SetFault((flag & 8) != 0); //blokada sprezarki if (flag & 16) //blokada wału { diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index 1b2ffe229..544866862 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -562,8 +562,8 @@ vehicle_table::update_brake_pipes( double const Deltatime ) { m_brakepipes.clear(); for( auto *vehicle : m_items ) { - if( ( true == vehicle->physics->brakePipe.couplersPending ) - || ( true == vehicle->physics->mainPipe.couplersPending ) ) { + if( ( true == vehicle->physics->brakePipe.CouplersPending() ) + || ( true == vehicle->physics->mainPipe.CouplersPending() ) ) { m_brakepipes.push_back( vehicle->physics ); } } @@ -690,7 +690,7 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio pipes.clear(); for( auto const index : members ) { auto *physics { m_items[ index ]->physics }; - if( physics->brakePipe.couplersPending || physics->mainPipe.couplersPending ) { + if( physics->brakePipe.CouplersPending() || physics->mainPipe.CouplersPending() ) { pipes.push_back( physics ); } } diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index 57c66c7d2..41e9d0220 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -74,7 +74,7 @@ void ui::vehicleparams_panel::draw_mini(const physics::Vehicle &physics) draw_infobutton(STR_C("main.")); if (physics.converter.IsRunning()) draw_infobutton(STR_C("conv.")); - if (physics.air.compressor.running) + if (physics.air.compressor.IsRunning()) draw_infobutton(STR_C("comp.")); if (physics.WarningSignal) @@ -154,8 +154,8 @@ void ui::vehicleparams_panel::render_contents() (true == physics.WaterHeater.is_damaged ? '!' : (physics.WaterHeater.is_active ? 'H' : (false == physics.WaterHeater.breaker ? '-' : (physics.WaterHeater.is_enabled ? 'h' : '.')))), (physics.FuelPump.is_active ? 'F' : (physics.FuelPump.is_enabled ? 'f' : '.')), (physics.OilPump.is_active ? 'O' : (physics.OilPump.is_enabled ? 'o' : '.')), (false == physics.converter.LocalSwitchOn() ? '-' : (physics.converter.IsAllowed() ? (physics.converter.IsRunning() ? 'X' : 'x') : '.')), (physics.converter.IsOverloaded() ? '!' : '.'), - (physics.air.compressor.running ? 'C' : (false == physics.air.compressor.allowLocal ? '-' : ((physics.air.compressor.allow || physics.air.compressor.start == start_t::automatic) ? 'c' : '.'))), - (physics.air.compressor.governorLock ? '!' : '.'), "", std::string(isdieselenginepowered ? STR(" oil pressure: ") + to_string(physics.OilPump.pressure, 2) : "").c_str(), + (physics.air.compressor.IsRunning() ? 'C' : (false == physics.air.compressor.LocalSwitchOn() ? '-' : ((physics.air.compressor.IsAllowed() || physics.air.compressor.config.start == start_t::automatic) ? 'c' : '.'))), + (physics.air.compressor.IsGovernorLocked() ? '!' : '.'), "", std::string(isdieselenginepowered ? STR(" oil pressure: ") + to_string(physics.OilPump.pressure, 2) : "").c_str(), // power transfers physics.Couplers[VehicleEnd::front].power_high.voltage, physics.Couplers[VehicleEnd::front].power_high.current, std::string(physics.Couplers[VehicleEnd::front].power_high.is_local ? "" : "-").c_str(), std::string(vehicle.DirectionGet() ? ":<<:" : ":>>:").c_str(), std::string(physics.Couplers[VehicleEnd::rear].power_high.is_local ? "" : "-").c_str(), @@ -205,9 +205,9 @@ void ui::vehicleparams_panel::render_contents() // cylinders physics.brakes.cylinderPressure, physics.brakes.independentCylinderPressure, physics.brakes.distributor->GetBrakeStatus(), // pipes - physics.brakePipe.pressure, physics.brakes.handleCapPosition, physics.mainPipe.pressure, physics.brakes.controlReservoirPressure, + physics.brakePipe.Pressure(), physics.brakes.handleCapPosition, physics.mainPipe.Pressure(), physics.brakes.controlReservoirPressure, // tanks - physics.brakes.distributor->GetBRP(), physics.air.mainReservoirPressure, physics.brakes.distributor->GetCRP()); + physics.brakes.distributor->GetBRP(), physics.air.MainReservoirPressure(), physics.brakes.distributor->GetCRP()); ImGui::TextUnformatted(buffer.data()); From fe6d3a1d187e4e234abdd5325fd9265362bbe383 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 29 Nov 2026 10:23:04 +0100 Subject: [PATCH 11/30] ci: build the binaries once per commit, and not for docs or scenario tests A pull request from a branch of this repository no longer builds the binaries: the push run of that branch builds the same commit and publishes its download, and the merge with the base is compiled by the Build and Coverage workflows. A pull request from a fork has no push run here and builds both variants as before. A push that changes only *.md, docs/, LICENSE or tests/scenarios/ builds nothing either (new branches are compared with staging, then master); pushes to staging and master and manual runs always build, and so does anything the check can't decide. The decision is a job (`changes`) the build jobs need, so a skipped build counts as passed. With the pull request builds gone, the AVX2-only matrix of a same-repository pull request is no longer needed and both jobs list their two variants again. Coverage skips tests/scenarios/ as well. --- .github/workflows/build_bin.yml | 102 ++++++++++++++++++++++++++++---- .github/workflows/coverage.yml | 9 +-- 2 files changed, 97 insertions(+), 14 deletions(-) diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index dc612e0fd..c2bfe2e64 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -23,6 +23,80 @@ env: jobs: + # ============================================================ + # Whether the binaries are built at all + # ============================================================ + + # Every push to a branch of this repository runs this workflow, and a pull request from such a branch would run it + # once more for the same commit. The push run builds and publishes the download of the branch, so the pull request + # run of a branch of this repository builds nothing (the merge with the base is compiled by the Build and Coverage + # workflows); a pull request from a fork has no push run here and builds as before. A push that changes only + # documentation or the data of the scenario tests (which the binaries don't contain) builds nothing either: the + # download of the branch stays at its last build, of the same binaries. Pushes to staging and master and manual runs + # always build. The checks are job-level conditions, not `paths-ignore` or `branches-ignore` on the trigger: a skipped + # job counts as passed, a workflow that doesn't start would leave a required check pending for ever (none is + # required today). Anything this job can't decide builds. + changes: + name: Whether to build + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + pull-requests: read + outputs: + build: ${{ steps.decide.outputs.build }} + steps: + - name: Decide from the event and the changed files + id: decide + env: + GH_TOKEN: ${{ github.token }} + EVENT_NAME: ${{ github.event_name }} + REPO: ${{ github.repository }} + REF: ${{ github.ref }} + SHA: ${{ github.sha }} + BEFORE: ${{ github.event.before }} + PR_NUMBER: ${{ github.event.pull_request.number }} + PR_HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }} + run: | + build() { echo "$1"; echo "build=true" >> "$GITHUB_OUTPUT"; exit 0; } + case "$EVENT_NAME" in + pull_request) + if [ "$PR_HEAD_REPO" = "$REPO" ]; then + echo "A branch of this repository: its push run builds this commit." + echo "build=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + files="$(gh api --paginate "repos/$REPO/pulls/$PR_NUMBER/files" --jq '.[] | .filename, (.previous_filename // empty)')" \ + || build "The files of the pull request are not available, building." ;; + push) + case "$REF" in + refs/heads/staging|refs/heads/master) build "A push to staging or master, building." ;; + esac + # a new branch (before = zeros) against staging, then master; a later push against the commit before it + if [ -n "$BEFORE" ] && [ "$BEFORE" != 0000000000000000000000000000000000000000 ]; then + bases="$BEFORE" + else + bases="staging master" + fi + files="" + for base in $bases; do + # the compare lists at most 300 files: more than that, or no list, builds + if out="$(gh api "repos/$REPO/compare/$base...$SHA" --jq 'if (.files | length) < 300 then (.files[] | .filename, (.previous_filename // empty)) else error("too many files") end')"; then + files="$out" + break + fi + done ;; + *) build "A manual run, building." ;; + esac + [ -n "$files" ] || build "The list of changed files is not available or empty, building." + # what the binaries don't contain: *.md, docs/, LICENSE and the scenario tests (cases and their runner) + # (not *.txt: CMakeLists.txt is code; tests/unit is built into the binaries' test run) + if printf '%s\n' "$files" | grep -Evq '(\.md$|^docs/|^LICENSE|^tests/scenarios/)'; then + build "Code changed, building." + fi + echo "Only documentation or scenario test data changed, the binaries are not built." + echo "build=false" >> "$GITHUB_OUTPUT" + # ============================================================ # Windows / MSVC # ============================================================ @@ -37,6 +111,8 @@ jobs: windows: name: Windows x64 / MSVC / ${{ matrix.variant.name }} + needs: changes + if: needs.changes.outputs.build == 'true' runs-on: windows-2022 concurrency: group: ${{ github.workflow }}-windows-${{ matrix.variant.suffix }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} @@ -45,11 +121,13 @@ jobs: strategy: fail-fast: false matrix: - # a pull request from a branch of this repository builds the AVX2 variant only; the variant without AVX2 - # (the same sources, one compiler switch) is built by the push of that branch, by the pushes to staging - # and master and by a manual run. a pull request from a fork has no push run here, so it builds both. - # so the "No AVX2" jobs of a pull request of this repository never run: don't make them a required check - variant: ${{ fromJSON(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"}]' || '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"},{"name":"No AVX2","suffix":"noavx2","cmake_flags":"-DENABLE_AVX2=OFF"}]') }} + variant: + - name: "AVX2" + suffix: "avx2" + cmake_flags: "-DENABLE_AVX2=ON" + - name: "No AVX2" + suffix: "noavx2" + cmake_flags: "-DENABLE_AVX2=OFF" steps: - name: Checkout repository @@ -204,6 +282,8 @@ jobs: linux: name: Linux x64 / GCC / ${{ matrix.variant.name }} + needs: changes + if: needs.changes.outputs.build == 'true' runs-on: ubuntu-24.04 # the key of a compiler cache saved here, one output per variant (a matrix job's outputs are shared by its legs): # the job linux-ccache-cleanup deletes the older ones, so this job needs no write access @@ -218,11 +298,13 @@ jobs: strategy: fail-fast: false matrix: - # a pull request from a branch of this repository builds the AVX2 variant only; the variant without AVX2 - # (the same sources, one compiler switch) is built by the push of that branch, by the pushes to staging - # and master and by a manual run. a pull request from a fork has no push run here, so it builds both. - # so the "No AVX2" jobs of a pull request of this repository never run: don't make them a required check - variant: ${{ fromJSON(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"}]' || '[{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON"},{"name":"No AVX2","suffix":"noavx2","cmake_flags":"-DENABLE_AVX2=OFF"}]') }} + variant: + - name: "AVX2" + suffix: "avx2" + cmake_flags: "-DENABLE_AVX2=ON" + - name: "No AVX2" + suffix: "noavx2" + cmake_flags: "-DENABLE_AVX2=OFF" steps: - name: Checkout repository diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index dbd79eee8..92fa748cd 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -28,7 +28,8 @@ concurrency: cancel-in-progress: true jobs: - # A pull request that changes only documentation doesn't need the coverage build. The check is a job-level + # A pull request that changes only documentation or the scenario tests (cases and their runner, which aren't built) + # doesn't need the coverage build. The check is a job-level # condition, not `paths-ignore` on the trigger: a workflow that doesn't start leaves a required check "pending" # for ever, while a skipped job (its name is fixed) counts as passed. A push, and anything this step can't # decide, runs the build. @@ -58,11 +59,11 @@ jobs: echo "code=true" >> "$GITHUB_OUTPUT" exit 0 fi - # what is not documentation: *.md, docs/ and LICENSE (not *.txt: CMakeLists.txt is code) - if printf '%s\n' "$files" | grep -Evq '(\.md$|^docs/|^LICENSE)'; then + # what is not built: *.md, docs/, LICENSE and tests/scenarios/ (not *.txt: CMakeLists.txt is code) + if printf '%s\n' "$files" | grep -Evq '(\.md$|^docs/|^LICENSE|^tests/scenarios/)'; then echo "code=true" >> "$GITHUB_OUTPUT" else - echo "Only documentation changed, the coverage build is skipped." + echo "Only documentation or scenario tests changed, the coverage build is skipped." echo "code=false" >> "$GITHUB_OUTPUT" fi From d0b8d689afc538a85618d377223eb002917276d1 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 10:24:00 +0100 Subject: [PATCH 12/30] refactor(physics): the blending of the brakes of a consist is a module of the physics The blending of the electrodynamic and the electropneumatic brakes over a consist driven by induction motors (the MED of the .fiz) moves out of TDynamicObject into physics::ConsistBrakeBlending (physics/consistbraking.*). It works on the physics of the vehicles alone, given in the order of the consist; TDynamicObject::distributeInductionBraking() only lists them from the occupied cab, as its loops walked them, and hands the result (the most deceleration of the service braking) to the driver. The state of the blending (the ED demand of the step before, the log of MEDLOGS/, the figures of the debug screen) goes with it. The code moves as it was: its arithmetic, its float and double conversions and the order of its steps are kept. Nothing in the unit tests reached it before, as they don't run TDynamicObject; now that it stands on its own, tests of it are added (test_consist_braking.cpp): the full braking demand over the mass of an Elf, the electropneumatic brake of every car standing, no demand at neutral. The figures of the debug screen start at zero rather than uninitialised for a vehicle that never led a consist. --- CMakeLists.txt | 1 + application/driveruipanels.cpp | 2 +- physics/consistbraking.cpp | 417 ++++++++++++++++++++++++++++ physics/consistbraking.h | 68 +++++ tests/unit/test_consist_braking.cpp | 108 +++++++ vehicle/DynObj.h | 20 +- vehicle/dynamic/lifecycle.cpp | 4 - vehicle/dynamic/update.cpp | 411 +-------------------------- 8 files changed, 609 insertions(+), 422 deletions(-) create mode 100644 physics/consistbraking.cpp create mode 100644 physics/consistbraking.h create mode 100644 tests/unit/test_consist_braking.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c5973e512..336507363 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -811,6 +811,7 @@ set(CORE_SOURCES "physics/components/setup.cpp" "physics/components/traction.cpp" "physics/couplerphysics.cpp" +"physics/consistbraking.cpp" "physics/derailment.cpp" "physics/collision.cpp" "vehicle/derailmotion.cpp" diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 6533dcbbc..8a333f4c4 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -1112,7 +1112,7 @@ debug_panel::update_section_engine( std::vector &Output ) const { parameters += " med:"; } else if( i >= 13 ) { - parameters += " | " + TDynamicObject::MED_labels[ i - 13 ] + to_string( vehicle.MED[ 0 ][ i - 13 ], 2, 9 ); + parameters += " | " + std::string( physics::ConsistBrakeBlending::Labels[ i - 13 ] ) + to_string( vehicle.brakeBlending.Figures()[ i - 13 ], 2, 9 ); } Output.emplace_back( parameters, Global.UITextColor ); diff --git a/physics/consistbraking.cpp b/physics/consistbraking.cpp new file mode 100644 index 000000000..f8218ffd2 --- /dev/null +++ b/physics/consistbraking.cpp @@ -0,0 +1,417 @@ +/* +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 "physics/consistbraking.h" + +#include +#include +#include + +#include "physics/vehicle.h" +#include "physics/brakes.h" +#include "utilities/utilities.h" + +// the state shared by the steps of the blending +struct physics::ConsistBrakeBlending::Step { + int np { 0 }; + double masa { 0.0 }; + double FrED { 0.0 }; + double masamax { 0.0 }; + double FmaxPN { 0.0 }; + double FfulED { 0.0 }; + double FmaxED { 0.0 }; + int osie { 0 }; + double eimic { 0.0 }; + double LBR { 0.0 }; + double eim_lb { 0.0 }; + double amax { 0.0 }; + bool doorisopen { false }; + double Fzad { 0.0 }; + double FzadED { 0.0 }; + double FzadPN { 0.0 }; + float nPrzekrF { 0.f }; +}; + +// the consist with induction motors driven and braked as a whole, its braking split between the ED and the EP brakes +double physics::ConsistBrakeBlending::Update(Vehicle &Lead, std::vector const &Consist, Inputs const &Given, double const dt1) +{ + Step state; + SetControl( state, Lead, Given, dt1 ); + SumForces( state, Consist ); + ComputeDeceleration( state, Lead ); + UpdateShuntMode( state, Lead ); + ComputeDemand( state, Lead, dt1 ); + OpenLog( state, Lead ); + ComputeElectrodynamicDemand( state, Lead, dt1 ); + DistributeForces( state, Lead, Consist, dt1 ); + Record( state, Lead, Consist, dt1 ); + + lastEdDemand = state.FzadED; + return state.amax; +} + +// step 0a of the blending: the demand of the integrated controller read and passed down the consist +void physics::ConsistBrakeBlending::SetControl(Step &state, Vehicle &Lead, Inputs const &Given, double const dt1) +{ + // 0a. ustal aktualna nastawe zadania sily napedowej i hamowania + if( Lead.Power < 1 + && Given.owner != nullptr ) { + Lead.MainCtrlPos = Given.owner->MainCtrlPos*Lead.MainCtrlPosNo / std::max(1, Given.owner->MainCtrlPosNo); + Lead.SpeedCtrlValue = Given.owner->SpeedCtrlValue; + Lead.SpeedCtrlUnit.IsActive = Given.owner->SpeedCtrlUnit.IsActive; + } + Lead.CheckEIMIC(dt1); + Lead.CheckSpeedCtrl(dt1); + + state.eimic = std::min(Lead.eimic, Lead.eimicSpeedCtrl); + Lead.eimic_real = state.eimic; + // Elf: full braking at once in the lowest position, and in the emergency brake position below it + if (Lead.EIMCtrlType == 2 && Lead.MainCtrlPos <= Lead.EIMCtrlEmergencyPositions()) + state.eimic = -1.0; + Lead.SendCtrlToNext(VehicleCommand::integratedController, std::max(0., state.eimic), Lead.CabActive); + state.LBR = std::max(-state.eimic, 0.); + state.eim_lb = Given.aiDriving || !Lead.brakes.independentTraxx ? 0 : Lead.eim_localbrake; +} + +// steps 1-2 of the blending: the masses and the most braking forces, pneumatic and ED, summed over the consist +void physics::ConsistBrakeBlending::SumForces(Step &state, std::vector const &Consist) +{ + auto FED { 0.0 }; + auto Frj { 0.0 }; + + // 1. ustal wymagana sile hamowania calego pociagu + // - opoznienie moze byc ustalane na podstawie charakterystyki + // - opoznienie moze byc ustalane na podstawie mas i cisnien granicznych + // + + // 2. ustal mozliwa do realizacji sile hamowania ED + // - w szczegolnosci powinien brac pod uwage rozne sily hamowania + for (auto *vehicle : Consist) + { + ++state.np; + state.masamax += + vehicle->brakes.maxPressureMass + + ( vehicle->brakes.maxPressureMass > 1.0 ? + 0.0 : + vehicle->Mass ) + + vehicle->Mred; + auto const Nmax = ((vehicle->brakes.pressureToForce * vehicle->brakes.maxCylinderPressure[0] - + vehicle->brakes.cylinders.springForce) * + vehicle->brakes.cylinders.leverRatio[0] - + vehicle->brakes.cylinders.slackAdjusterForce) * + vehicle->brakes.cylinders.count * vehicle->brakes.cylinders.riggingEfficiency; + state.FmaxPN += Nmax * vehicle->brakes.distributor->GetFC( + Nmax / (vehicle->NAxles * vehicle->brakes.blocksPerAxle), + vehicle->brakes.blending.referenceSpeed) * + 1000; // sila hamowania pn + state.FmaxED += vehicle->lineBreaker.IsClosed() && vehicle->DirActive != 0 && vehicle->inductionMotor.inverterRatio == 1.0 && + vehicle->inductionMotor.braking.maxForce * vehicle->NPoweredAxles > 0 ? + vehicle->inductionMotor.braking.maxForce * 1000 : + 0; // chwilowy max ED -> do rozdzialu sil + FED -= std::min(vehicle->inductionMotor.state.maxForce, 0.0) * + 1000; // chwilowy max ED -> do rozdzialu sil + state.FfulED = std::min(vehicle->inductionMotor.state.fullForce, 0.0) * + 1000; // chwilowy max ED -> do rozdzialu sil + state.FrED -= std::min(vehicle->inductionMotor.state.maxForce, 0.0) * + 1000; // chwilowo realizowane ED -> do pneumatyki + Frj += std::max(vehicle->inductionMotor.state.maxForce, 0.0) * + 1000;// chwilowo realizowany napęd -> do utrzymującego + state.masa += vehicle->TotalMass; + state.osie += vehicle->NAxles; + } +} + +// the most deceleration of the service braking of the consist, given to the driver too +void physics::ConsistBrakeBlending::ComputeDeceleration(Step &state, Vehicle const &Lead) +{ + double RapidMult = 1.0; + if ((Lead.brakes.availableDelays & bdelay_P + bdelay_R) == bdelay_P + bdelay_R + && Lead.brakes.delaySetting & bdelay_P) + RapidMult = Lead.brakes.rapidRatio; + + state.amax = RapidMult * std::min(state.FmaxPN / state.masamax, Lead.brakes.blending.maxDeceleration); + +} + +// the doors open or closed, and from them, the demand and the speed the shunting mode (the holding brake) of the consist +void physics::ConsistBrakeBlending::UpdateShuntMode(Step &state, Vehicle &Lead) +{ + state.doorisopen = + false == Lead.Doors.instances[VehicleSide::left].is_closed + || false == Lead.Doors.instances[VehicleSide::right].is_closed + || ( Lead.Doors.permit_needed + && ( Lead.Doors.instances[ VehicleSide::left ].open_permit + || Lead.Doors.instances[ VehicleSide::right ].open_permit ) ); + state.doorisopen &= !(Lead.brakes.spring.releasesParkingWithDoorOpen && Lead.brakes.spring.isActive); + + if (Lead.Vel < 0.5 && (state.eimic < 0 || state.doorisopen || Lead.brakes.distributor->GetEDBCP())) + { + Lead.ShuntMode = true; + } + if (Lead.ShuntMode) + { + Lead.ShuntModeAllow = false == state.doorisopen && + state.LBR < 0.01; + } + if( Lead.Vel > 1 && false == state.doorisopen ) + { + Lead.ShuntMode = false; + Lead.ShuntModeAllow = Lead.brakes.cylinderPressure > 0.2 && + state.LBR < 0.01; + } +} +// the braking force demanded of the whole consist +void physics::ConsistBrakeBlending::ComputeDemand(Step &state, Vehicle &Lead, double const dt1) +{ + state.Fzad = state.amax * state.LBR * state.masa; + if ((Lead.brakes.handlePosition == Lead.brakes.driverValve->GetPos(bh_EB) + && Lead.inductionMotor.braking.cylinderPressureGain < 0.001) || + Lead.brakes.emergencyValve.flow > 0) + state.Fzad = state.amax * state.masa; //pętla bezpieczeństwa - pełne służbowe + if (Lead.ScndS && + Lead.Vel > Lead.inductionMotor.braking.fullSpeed && state.FmaxED > 0) + { + state.Fzad = std::min(state.LBR * state.FmaxED, state.FfulED); + } + // the holding brake lets go once power has been demanded for its delay (SBDReleaseDelay, none by default) + auto const holdingbrakereleased { Lead.UpdateStopBrakeRelease( state.eimic, dt1 ) }; + if (Lead.ShuntMode && false == holdingbrakereleased || state.doorisopen /*|| + (Lead.V * Lead.DirAbsolute < -0.2)*/) + { + auto const sbd { ( Lead.brakes.spring.isActive && Lead.brakes.spring.releasesParking ? 0.0 : Lead.brakes.holding.deceleration ) }; + state.Fzad = std::max( state.Fzad, sbd * state.masa ); + } +} + +// the log of the braking of the consist opened, once it brakes while moving +void physics::ConsistBrakeBlending::OpenLog(Step const &state, Vehicle const &Lead) +{ + if (state.Fzad > 1 && !log.is_open() && Lead.Vel > 1) + { + log.open( + "MEDLOGS/" + Lead.Name + "_" + std::to_string( ++logCount ) + ".csv", + std::ios::in | std::ios::out | std::ios::trunc ); + log << "t\tVel\tMasa\tOsie\tFmaxPN\tFmaxED\tFfulED\tFrED\tFzad\tFzadED\tFzadPN"; + for(int k=1;k<=state.np;k++) + { + log << "\tBP" << k; + } + log << "\n"; + log.flush(); + logInactiveTime = 0; + logTime = 0; + } +} + +// the part of the demand the ED brake takes, brought in with a delay, and the rest left to the pneumatic brake +void physics::ConsistBrakeBlending::ComputeElectrodynamicDemand(Step &state, Vehicle &Lead, double const dt1) const +{ + state.FzadED = 0.0; + if( state.LBR > Lead.brakes.blending.minEdDemand + && ( Lead.brakes.driverValveType == TBrakeHandle::MHZ_EN57 ? + (Lead.brakes.operatingMode & bom_MED) != 0 : + Lead.EpFuse ) ) { + state.FzadED = std::min( state.Fzad, state.FmaxED ); + } + /*/ELF - wdrazanie ED po powrocie na utrzymanie hamowania - do usuniecia + if (Lead.EIMCtrlType == 2 && Lead.MainCtrlPos < 2 && Lead.eimic > -0.999) + { + FzadED = std::min(FzadED, lastEdDemand); + } //*/ + //opoznienie wdrazania ED + if (state.FzadED > lastEdDemand) + { + if (Lead.brakes.blending.edDelayTimer <= 0) { + Lead.brakes.blending.edDelayTimer += dt1; + if (Lead.brakes.blending.edDelayTimer > 0) { + + } + else { + state.FzadED = std::min(state.FzadED, lastEdDemand); + } + } + else + { + state.FzadED = std::min(state.FzadED, lastEdDemand); + Lead.brakes.blending.edDelayTimer = state.FrED > 0 ? -Lead.brakes.blending.edNextDelay : -Lead.brakes.blending.edFirstDelay; + } + } + if (Lead.brakes.handlePosition == Lead.brakes.driverValve->GetPos(bh_EB) + && Lead.inductionMotor.braking.cylinderPressureGain < 0.001) + state.FzadED = 0; //pętla bezpieczeństwa - bez ED + state.FzadPN = state.Fzad - state.FrED * Lead.brakes.blending.edForceFactor; +} +// steps 3-6 of the blending: the ED and the pneumatic braking forces set to the vehicles of the consist +void physics::ConsistBrakeBlending::DistributeForces(Step &state, Vehicle const &Lead, std::vector const &Consist, double const dt1) +{ + std::vector PrzekrF( state.np ); + state.nPrzekrF = 0; + bool test = true; + std::vector FzED( state.np ); + std::vector FzEP( state.np ); + std::vector FmaxEP( state.np ); + // 3. ustaw pojazdom sile hamowania ED + // - proporcjonalnie do mozliwosci + + // 4. ustal potrzebne dohamowanie pneumatyczne + // - od sily zadanej trzeba odjac realizowana przez ED + // 5. w razie potrzeby wlacz hamulec utrzymujacy + // - gdy zahamowany ma ponizej 2 km/h + // 6. ustaw pojazdom sile hamowania ep + // - proporcjonalnie do masy, do liczby osi, rowne cisnienia - jak + // bedzie, tak bedzie dobrze + float Fpoj = 0; // Lead.CabOccupied < 0 + ////ALGORYTM 2 - KAZDEMU PO ROWNO, ale nie wiecej niz eped * masa + // 1. najpierw daj kazdemu tyle samo + int i = 0; + for (auto *vehicle : Consist) + { + auto const Nmax = ((vehicle->brakes.pressureToForce * vehicle->brakes.maxCylinderPressure[0] - + vehicle->brakes.cylinders.springForce) * + vehicle->brakes.cylinders.leverRatio[0] - + vehicle->brakes.cylinders.slackAdjusterForce) * + vehicle->brakes.cylinders.count * vehicle->brakes.cylinders.riggingEfficiency; + FmaxEP[i] = Nmax * + vehicle->brakes.distributor->GetFC( + Nmax / (vehicle->NAxles * vehicle->brakes.blocksPerAxle), + vehicle->brakes.blending.referenceSpeed) * + 1000; // sila hamowania pn + + PrzekrF[i] = false; + FzED[i] = state.FmaxED > 0 ? state.FzadED / state.FmaxED : 0; + vehicle->AnPos = + Lead.ScndS ? state.LBR : FzED[i]; + FzEP[ i ] = static_cast( state.FzadPN * vehicle->NAxles ) / static_cast( state.osie ); + ++i; + vehicle->ShuntMode = Lead.ShuntMode; + vehicle->ShuntModeAllow = Lead.ShuntModeAllow; + } + while (test) + { + test = false; + i = 0; + float przek = 0; + for (auto *vehicle : Consist) + { + if (FzEP[i] > 0.01 && + FzEP[i] > vehicle->TotalMass * vehicle->inductionMotor.braking.maxEpDeceleration + std::min(vehicle->inductionMotor.state.maxForce, 0.) * 1000 && + !PrzekrF[i]) + { + float przek1 = -std::min(vehicle->inductionMotor.state.maxForce, 0.) * 1000 + + FzEP[i] - + vehicle->TotalMass * + vehicle->inductionMotor.braking.maxEpDeceleration * 0.999; + PrzekrF[i] = true; + test = true; + state.nPrzekrF++; + przek1 = std::min(przek1, FzEP[i]); + FzEP[i] -= przek1; + if (FzEP[i] < 0) + FzEP[i] = 0; + przek += przek1; + } + ++i; + } + i = 0; + przek = przek / (state.np - state.nPrzekrF); + for (auto *vehicle : Consist) + { + if (!PrzekrF[i]) + { + FzEP[i] += przek; + } + ++i; + } + } + i = 0; + for (auto *vehicle : Consist) + { + float Nmax = ((vehicle->brakes.pressureToForce * vehicle->brakes.maxCylinderPressure[0] - + vehicle->brakes.cylinders.springForce) * + vehicle->brakes.cylinders.leverRatio[0] - + vehicle->brakes.cylinders.slackAdjusterForce) * + vehicle->brakes.cylinders.count * vehicle->brakes.cylinders.riggingEfficiency; + if (state.FrED > 0.1) + vehicle->brakes.blending.epCorrectionTimer = 0; + else + vehicle->brakes.blending.epCorrectionTimer += dt1; + bool EPVC = vehicle->brakes.blending.epCorrection && (vehicle->brakes.blending.epCorrectionTime < 0 || vehicle->brakes.blending.epCorrectionTimer < vehicle->brakes.blending.epCorrectionTime); + float VelC = EPVC ? safe_clamp(vehicle->Vel, vehicle->brakes.blending.minSpeed, vehicle->brakes.blending.maxSpeed) : vehicle->brakes.blending.referenceSpeed;//korekcja EP po prędkości + float FmaxPoj = Nmax * + vehicle->brakes.distributor->GetFC( + Nmax / (vehicle->NAxles * vehicle->brakes.blocksPerAxle), VelC) * + 1000; // sila hamowania pn + vehicle->brakes.independentPositionEim = FzEP[i] / FmaxPoj; + if (vehicle->brakes.independentPositionEim>0.009) + if (vehicle->brakes.pressureToForce * vehicle->brakes.cylinders.leverRatio[0] * + vehicle->brakes.maxCylinderPressure[0] != 0) + { + float x = (vehicle->brakes.cylinders.slackAdjusterForce / vehicle->brakes.cylinders.leverRatio[0] + + vehicle->brakes.cylinders.springForce) / (vehicle->brakes.pressureToForce * + vehicle->brakes.maxCylinderPressure[0]); + vehicle->brakes.independentPositionEim = x + (1 - x) * vehicle->brakes.independentPositionEim; + } + else + vehicle->brakes.independentPositionEim = vehicle->brakes.independentPositionEim; + else + vehicle->brakes.independentPositionEim = 0; + if (vehicle->brakes.independentTraxx) + { + vehicle->eim_localbrake = state.eim_lb; + vehicle->brakes.independentPositionEim = std::max(vehicle->brakes.independentPositionEim, state.eim_lb); + } + ++i; + } +} + +// the state of the blending kept for the debug screen, and written to the log of the braking while it is open +void physics::ConsistBrakeBlending::Record(Step const &state, Vehicle const &Lead, std::vector const &Consist, double const dt1) +{ + figures[0] = state.masa*0.001; + figures[1] = state.amax; + figures[2] = state.Fzad*0.001; + figures[3] = state.FmaxPN*0.001; + figures[4] = state.FmaxED*0.001; + figures[5] = state.FrED*0.001; + figures[6] = state.FzadPN*0.001; + figures[7] = state.nPrzekrF; + + if (log.is_open()) + { + log << logTime << "\t" << Lead.Vel << "\t" << state.masa*0.001 << "\t" << state.osie << "\t" << state.FmaxPN*0.001 << "\t" << state.FmaxED*0.001 << "\t" + << state.FfulED*0.001 << "\t" << state.FrED*0.001 << "\t" << state.Fzad*0.001 << "\t" << state.FzadED*0.001 << "\t" << state.FzadPN*0.001; + for (auto *vehicle : Consist) + { + log << "\t" << vehicle->brakes.cylinderPressure; + } + log << "\n"; + if (floor(logTime + dt1) > floor(logTime)) + { + log.flush(); + } + logTime += dt1; + + if (Lead.Vel < 0.1 || Lead.MainCtrlPowerPos() > 0) + { + logInactiveTime += dt1; + } + else + { + logInactiveTime = 0; + } + if (logInactiveTime > 5) + { + log.flush(); + log.close(); + } + + } +} + diff --git a/physics/consistbraking.h b/physics/consistbraking.h new file mode 100644 index 000000000..bef61ff4c --- /dev/null +++ b/physics/consistbraking.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/. +*/ + +// the braking of a consist driven by induction motors as a whole: the vehicle with the driver blends the electrodynamic +// (ED) brakes of the consist with its electropneumatic (EP) ones (the MED of the .fiz), and sets the holding brake. +// it works on the physics of the vehicles alone, given in the order of the consist from the occupied cab + +#pragma once + +#include +#include +#include +#include +#include + +namespace physics +{ + +class Vehicle; + +class ConsistBrakeBlending +{ + public: + // what the blending needs to know beside the vehicles + struct Inputs + { + // the vehicle whose controller an unpowered lead vehicle (a driving trailer) follows, nullptr when none + Vehicle const *owner{nullptr}; + bool aiDriving{false}; // the AI drives: it brakes the locomotive brake of a TRAXX-like handle itself + }; + + // the step of the blending, from the lead vehicle over its consist (the lead among them). returns the most + // deceleration of the service braking of the consist, which the driver goes by + double Update(Vehicle &Lead, std::vector const &Consist, Inputs const &Given, double dt); + + // the figures of the last step for the debug screen, in the order of Labels + static constexpr std::array Labels{"masa: ", "amax: ", "Fzad: ", "FmPN: ", "FmED: ", "FrED: ", "FzPN: ", "nPrF: "}; + std::array const &Figures() const { return figures; } + + private: + struct Step; + + static void SetControl(Step &State, Vehicle &Lead, Inputs const &Given, double dt); + static void SumForces(Step &State, std::vector const &Consist); + static void ComputeDeceleration(Step &State, Vehicle const &Lead); + static void UpdateShuntMode(Step &State, Vehicle &Lead); + static void ComputeDemand(Step &State, Vehicle &Lead, double dt); + void OpenLog(Step const &State, Vehicle const &Lead); + void ComputeElectrodynamicDemand(Step &State, Vehicle &Lead, double dt) const; + static void DistributeForces(Step &State, Vehicle const &Lead, std::vector const &Consist, double dt); + void Record(Step const &State, Vehicle const &Lead, std::vector const &Consist, double dt); + + double lastEdDemand{0.0}; // the demand of the ED brake of the step before [N] + std::array figures{}; + // the log of the braking (MEDLOGS/), opened while the consist brakes moving + std::ofstream log; + double logTime{0.0}; + double logInactiveTime{0.0}; + int logCount{0}; +}; + +} // namespace physics diff --git a/tests/unit/test_consist_braking.cpp b/tests/unit/test_consist_braking.cpp new file mode 100644 index 000000000..1fbb16284 --- /dev/null +++ b/tests/unit/test_consist_braking.cpp @@ -0,0 +1,108 @@ +#include "stdafx.h" +#include "doctest.h" +#include "consist.h" +#include "drive.h" + +#include "physics/consistbraking.h" +#include "physics/brakes.h" + +#include + +// the blending of the brakes of a consist driven by induction motors (physics::ConsistBrakeBlending, the MED of the +// .fiz), which the game runs from the vehicle with the driver (TDynamicObject::distributeInductionBraking()) + +using test::definition; + +namespace { + +// a three-car Elf ready to run, standing with its brakes released, driven from the front cab of the head car +struct elf { + elf() { + for (auto const *car : {"elf_v1/21we-a", "elf_v1/21we-b", "elf_v1/21we-c"}) { + unit.add(definition::fiz(car), unit.size() == 0 ? 1 : 0); + } + ready = test::start_up(test::driving(unit), line); + for (int i = 0; i < 3 && cab().DirActive <= 0; ++i) { + cab().DirectionForward(); + } + test::release_brakes(cab()); + for (std::size_t index = 0; index < unit.size(); ++index) { + cars.emplace_back(&unit[index].physics()); + } + } + physics::Vehicle &cab() { return unit[0].physics(); } + // the steps of the game: the physics of the cars, then the blending from the head car + double step(double Seconds, double Dt = 0.01) { + auto amax{0.0}; + for (auto time{0.0}; time < Seconds; time += Dt) { + unit.step(line, Dt); + amax = blending.Update(cab(), cars, {}, Dt); + } + return amax; + } + test::consist unit; + test::track line{0.0, 0.0, test::catenary_3kv}; + std::vector cars; + physics::ConsistBrakeBlending blending; + bool ready{false}; +}; + +// the figures of the debug screen, by their labels +constexpr std::size_t mass{0}; // [t] +constexpr std::size_t deceleration{1}; // the most of the service braking [m/s2] +constexpr std::size_t demand{2}; // [kN] + +} // namespace + +TEST_CASE("consist braking: the full braking position demands the most deceleration of the consist, over all its mass") { + elf unit; + REQUIRE(unit.ready); + unit.cab().MainCtrlPos = 0; // the full braking position of the Elf's controller + auto const amax{unit.step(2.0)}; + CHECK(amax > 0.0); + CHECK(amax <= unit.cab().brakes.blending.maxDeceleration); + auto const &figures{unit.blending.Figures()}; + CHECK(figures[deceleration] == doctest::Approx(amax)); + auto mass_t{0.0}; + for (auto const *car : unit.cars) { + mass_t += car->TotalMass * 0.001; + } + CHECK(figures[mass] == doctest::Approx(mass_t)); + // the holding brake standing still asks for no more than the service braking does + CHECK(figures[demand] == doctest::Approx(amax * mass_t)); +} + +TEST_CASE("consist braking: standing at full braking, every car brakes with its electropneumatic brake") { + elf unit; + REQUIRE(unit.ready); + unit.cab().MainCtrlPos = 0; + unit.step(2.0); + for (auto const *car : unit.cars) { + CAPTURE(car->Name); + CHECK(car->brakes.independentPositionEim > 0.0); + CHECK(car->brakes.independentPositionEim <= 1.0); + // the shunting mode (the holding brake) of the head car goes to all of them + CHECK(car->ShuntMode == unit.cab().ShuntMode); + } +} + +TEST_CASE("consist braking: with the controller at neutral and the train released, moving, nothing is demanded") { + elf unit; + REQUIRE(unit.ready); + while (unit.cab().MainCtrlPos < unit.cab().MainCtrlNoPowerPos() && unit.cab().IncMainCtrl(1)) { + // up to neutral + } + // the controller's demand comes back from full braking to nothing gradually + unit.step(10.0); + REQUIRE(unit.cab().eimic == doctest::Approx(0.0)); + for (auto *car : unit.cars) { + car->V = 10.0; // [m/s], above the speed the holding brake comes in at + car->Vel = 36.0; + } + unit.blending.Update(unit.cab(), unit.cars, {}, 0.01); + CHECK(unit.blending.Figures()[demand] == doctest::Approx(0.0)); + for (auto const *car : unit.cars) { + CAPTURE(car->Name); + CHECK(car->brakes.independentPositionEim == doctest::Approx(0.0)); + } +} diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index b6905c363..0e670f1d2 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "model/materialdata.h" #include "physics/vehicletypes.h" #include "physics/derailment.h" +#include "physics/consistbraking.h" #include "vehicle/derailmotion.h" #include "world/TrkFoll.h" #include "vehicle/Button.h" @@ -757,21 +758,11 @@ private: bool Update(double dt, double dt1); private: // the steps of Update() (vehicle/dynamic/update.cpp) - struct InductionBrakeState; void updateTrackParameters(); void updateCouplingState(); void updateTractionVoltage( double dt1 ); void updateDriver( double dt1 ); void distributeInductionBraking( double dt1 ); - void setInductionControl( InductionBrakeState &state, double dt1 ); - void sumConsistBrakeForces( InductionBrakeState &state ); - void computeBrakeDeceleration( InductionBrakeState &state ); - void updateShuntMode( InductionBrakeState &state ); - void computeBrakeDemand( InductionBrakeState &state, double dt1 ); - void openMedLog( InductionBrakeState const &state ); - void computeElectrodynamicDemand( InductionBrakeState &state, double dt1 ); - void distributeBrakeForces( InductionBrakeState &state, double dt1 ); - void recordMedState( InductionBrakeState const &state, double dt1 ); void switchOffMainsWithoutBattery(); double moveByPhysics( double dt, double dt1 ); void updateAxleClatter( double dDOMoveLen ); @@ -1036,13 +1027,8 @@ public: float soundproofing( int const Placement, int const Listener ) const { return m_soundproofing[ Placement - 1 ][ Listener + 1 ]; } - double MED[9][8]; // lista zmiennych do debugowania hamulca ED - static std::string const MED_labels[ 8 ]; - std::ofstream MEDLogFile; // zapis parametrów hamowania - double MEDLogTime = 0; - double MEDLogInactiveTime = 0; - int MEDLogCount = 0; - double MED_oldFED = 0; + // the blending of the ED and EP brakes of the consist this vehicle leads, with induction motors + physics::ConsistBrakeBlending brakeBlending; // vehicle shaking calculations // TBD, TODO: make an object out of it diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index f9fac57ff..2857bdaf3 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -59,10 +59,6 @@ http://mozilla.org/MPL/2.0/. const float maxrot = (float)(M_PI / 3.0); // 60° -std::string const TDynamicObject::MED_labels[] = { - "masa: ", "amax: ", "Fzad: ", "FmPN: ", "FmED: ", "FrED: ", "FzPN: ", "nPrF: " -}; - bool TDynamicObject::bDynamicRemove { false }; // helper, locates submodel with specified name in specified 3d model; returns: pointer to the submodel, or null diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index ffff2a58a..cb4d0f1a8 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -325,409 +325,20 @@ void TDynamicObject::updateDriver( double const dt1 ) Timer::subsystem.vehicles_ai.stop(); } -// the state shared by the steps of the blending of the brakes over a consist with induction motors -struct TDynamicObject::InductionBrakeState { - bool kier { false }; - int np { 0 }; - double masa { 0.0 }; - double FrED { 0.0 }; - double masamax { 0.0 }; - double FmaxPN { 0.0 }; - double FfulED { 0.0 }; - double FmaxED { 0.0 }; - int osie { 0 }; - double eimic { 0.0 }; - double LBR { 0.0 }; - double eim_lb { 0.0 }; - double amax { 0.0 }; - bool doorisopen { false }; - double Fzad { 0.0 }; - double FzadED { 0.0 }; - double FzadPN { 0.0 }; - float nPrzekrF { 0.f }; -}; - -// the consist with induction motors driven and braked as a whole, its braking split between the ED and the EP brakes +// the consist with induction motors driven and braked as a whole: its braking blended between the ED and the EP brakes +// (physics::ConsistBrakeBlending), over the vehicles in their order from the occupied cab void TDynamicObject::distributeInductionBraking( double const dt1 ) { - InductionBrakeState state; - state.kier = DirectionGet() * physics->CabOccupied > 0; - setInductionControl( state, dt1 ); - sumConsistBrakeForces( state ); - computeBrakeDeceleration( state ); - updateShuntMode( state ); - computeBrakeDemand( state, dt1 ); - openMedLog( state ); - computeElectrodynamicDemand( state, dt1 ); - distributeBrakeForces( state, dt1 ); - recordMedState( state, dt1 ); - - MED_oldFED = state.FzadED; -} - -// step 0a of the blending: the demand of the integrated controller read and passed down the consist -void TDynamicObject::setInductionControl( InductionBrakeState &state, double const dt1 ) -{ - // 0a. ustal aktualna nastawe zadania sily napedowej i hamowania - if( physics->Power < 1 - && ctOwner != nullptr ) { - physics->MainCtrlPos = ctOwner->Controlling()->MainCtrlPos*physics->MainCtrlPosNo / std::max(1, ctOwner->Controlling()->MainCtrlPosNo); - physics->SpeedCtrlValue = ctOwner->Controlling()->SpeedCtrlValue; - physics->SpeedCtrlUnit.IsActive = ctOwner->Controlling()->SpeedCtrlUnit.IsActive; - } - physics->CheckEIMIC(dt1); - physics->CheckSpeedCtrl(dt1); - - state.eimic = std::min(physics->eimic, physics->eimicSpeedCtrl); - physics->eimic_real = state.eimic; - // Elf: full braking at once in the lowest position, and in the emergency brake position below it - if (physics->EIMCtrlType == 2 && physics->MainCtrlPos <= physics->EIMCtrlEmergencyPositions()) - state.eimic = -1.0; - physics->SendCtrlToNext(VehicleCommand::integratedController, std::max(0., state.eimic), physics->CabActive); - state.LBR = std::max(-state.eimic, 0.); - state.eim_lb = Mechanik->AIControllFlag || !physics->brakes.independentTraxx ? 0 : physics->eim_localbrake; -} - -// steps 1-2 of the blending: the masses and the most braking forces, pneumatic and ED, summed over the consist -void TDynamicObject::sumConsistBrakeForces( InductionBrakeState &state ) -{ - auto FED { 0.0 }; - auto Frj { 0.0 }; - - // 1. ustal wymagana sile hamowania calego pociagu - // - opoznienie moze byc ustalane na podstawie charakterystyki - // - opoznienie moze byc ustalane na podstawie mas i cisnien granicznych - // - - // 2. ustal mozliwa do realizacji sile hamowania ED - // - w szczegolnosci powinien brac pod uwage rozne sily hamowania - for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; - state.kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) - { - ++state.np; - state.masamax += - p->physics->brakes.maxPressureMass - + ( p->physics->brakes.maxPressureMass > 1.0 ? - 0.0 : - p->physics->Mass ) - + p->physics->Mred; - auto const Nmax = ((p->physics->brakes.pressureToForce * p->physics->brakes.maxCylinderPressure[0] - - p->physics->brakes.cylinders.springForce) * - p->physics->brakes.cylinders.leverRatio[0] - - p->physics->brakes.cylinders.slackAdjusterForce) * - p->physics->brakes.cylinders.count * p->physics->brakes.cylinders.riggingEfficiency; - state.FmaxPN += Nmax * p->physics->brakes.distributor->GetFC( - Nmax / (p->physics->NAxles * p->physics->brakes.blocksPerAxle), - p->physics->brakes.blending.referenceSpeed) * - 1000; // sila hamowania pn - state.FmaxED += p->physics->lineBreaker.IsClosed() && p->physics->DirActive != 0 && p->physics->inductionMotor.inverterRatio == 1.0 && - p->physics->inductionMotor.braking.maxForce * p->physics->NPoweredAxles > 0 ? - p->physics->inductionMotor.braking.maxForce * 1000 : - 0; // chwilowy max ED -> do rozdzialu sil - FED -= std::min(p->physics->inductionMotor.state.maxForce, 0.0) * - 1000; // chwilowy max ED -> do rozdzialu sil - state.FfulED = std::min(p->physics->inductionMotor.state.fullForce, 0.0) * - 1000; // chwilowy max ED -> do rozdzialu sil - state.FrED -= std::min(p->physics->inductionMotor.state.maxForce, 0.0) * - 1000; // chwilowo realizowane ED -> do pneumatyki - Frj += std::max(p->physics->inductionMotor.state.maxForce, 0.0) * - 1000;// chwilowo realizowany napęd -> do utrzymującego - state.masa += p->physics->TotalMass; - state.osie += p->physics->NAxles; - } -} - -// the most deceleration of the service braking of the consist, given to the driver too -void TDynamicObject::computeBrakeDeceleration( InductionBrakeState &state ) -{ - double RapidMult = 1.0; - if ((physics->brakes.availableDelays & bdelay_P + bdelay_R) == bdelay_P + bdelay_R - && physics->brakes.delaySetting & bdelay_P) - RapidMult = physics->brakes.rapidRatio; - - state.amax = RapidMult * std::min(state.FmaxPN / state.masamax, physics->brakes.blending.maxDeceleration); - - Mechanik->fMedAmax = state.amax; -} - -// the doors open or closed, and from them, the demand and the speed the shunting mode (the holding brake) of the consist -void TDynamicObject::updateShuntMode( InductionBrakeState &state ) -{ - state.doorisopen = - false == physics->Doors.instances[VehicleSide::left].is_closed - || false == physics->Doors.instances[VehicleSide::right].is_closed - || ( physics->Doors.permit_needed - && ( physics->Doors.instances[ VehicleSide::left ].open_permit - || physics->Doors.instances[ VehicleSide::right ].open_permit ) ); - state.doorisopen &= !(physics->brakes.spring.releasesParkingWithDoorOpen && physics->brakes.spring.isActive); - - if (physics->Vel < 0.5 && (state.eimic < 0 || state.doorisopen || physics->brakes.distributor->GetEDBCP())) - { - physics->ShuntMode = true; - } - if (physics->ShuntMode) - { - physics->ShuntModeAllow = false == state.doorisopen && - state.LBR < 0.01; - } - if( physics->Vel > 1 && false == state.doorisopen ) - { - physics->ShuntMode = false; - physics->ShuntModeAllow = physics->brakes.cylinderPressure > 0.2 && - state.LBR < 0.01; - } -} -// the braking force demanded of the whole consist -void TDynamicObject::computeBrakeDemand( InductionBrakeState &state, double const dt1 ) -{ - state.Fzad = state.amax * state.LBR * state.masa; - if ((physics->brakes.handlePosition == physics->brakes.driverValve->GetPos(bh_EB) - && physics->inductionMotor.braking.cylinderPressureGain < 0.001) || - physics->brakes.emergencyValve.flow > 0) - state.Fzad = state.amax * state.masa; //pętla bezpieczeństwa - pełne służbowe - if (physics->ScndS && - physics->Vel > physics->inductionMotor.braking.fullSpeed && state.FmaxED > 0) - { - state.Fzad = std::min(state.LBR * state.FmaxED, state.FfulED); - } - // the holding brake lets go once power has been demanded for its delay (SBDReleaseDelay, none by default) - auto const holdingbrakereleased { physics->UpdateStopBrakeRelease( state.eimic, dt1 ) }; - if (physics->ShuntMode && false == holdingbrakereleased || state.doorisopen /*|| - (physics->V * physics->DirAbsolute < -0.2)*/) - { - auto const sbd { ( physics->brakes.spring.isActive && physics->brakes.spring.releasesParking ? 0.0 : physics->brakes.holding.deceleration ) }; - state.Fzad = std::max( state.Fzad, sbd * state.masa ); - } -} - -// the log of the braking of the consist opened, once it brakes while moving -void TDynamicObject::openMedLog( InductionBrakeState const &state ) -{ - if (state.Fzad > 1 && !MEDLogFile.is_open() && physics->Vel > 1) - { - MEDLogFile.open( - "MEDLOGS/" + physics->Name + "_" + std::to_string( ++MEDLogCount ) + ".csv", - std::ios::in | std::ios::out | std::ios::trunc ); - MEDLogFile << "t\tVel\tMasa\tOsie\tFmaxPN\tFmaxED\tFfulED\tFrED\tFzad\tFzadED\tFzadPN"; - for(int k=1;k<=state.np;k++) - { - MEDLogFile << "\tBP" << k; - } - MEDLogFile << "\n"; - MEDLogFile.flush(); - MEDLogInactiveTime = 0; - MEDLogTime = 0; - } -} - -// the part of the demand the ED brake takes, brought in with a delay, and the rest left to the pneumatic brake -void TDynamicObject::computeElectrodynamicDemand( InductionBrakeState &state, double const dt1 ) -{ - state.FzadED = 0.0; - if( state.LBR > physics->brakes.blending.minEdDemand - && ( physics->brakes.driverValveType == TBrakeHandle::MHZ_EN57 ? - (physics->brakes.operatingMode & bom_MED) != 0 : - physics->EpFuse ) ) { - state.FzadED = std::min( state.Fzad, state.FmaxED ); - } - /*/ELF - wdrazanie ED po powrocie na utrzymanie hamowania - do usuniecia - if (physics->EIMCtrlType == 2 && physics->MainCtrlPos < 2 && physics->eimic > -0.999) - { - FzadED = std::min(FzadED, MED_oldFED); - } //*/ - //opoznienie wdrazania ED - if (state.FzadED > MED_oldFED) - { - if (physics->brakes.blending.edDelayTimer <= 0) { - physics->brakes.blending.edDelayTimer += dt1; - if (physics->brakes.blending.edDelayTimer > 0) { - - } - else { - state.FzadED = std::min(state.FzadED, MED_oldFED); - } - } - else - { - state.FzadED = std::min(state.FzadED, MED_oldFED); - physics->brakes.blending.edDelayTimer = state.FrED > 0 ? -physics->brakes.blending.edNextDelay : -physics->brakes.blending.edFirstDelay; - } - } - if (physics->brakes.handlePosition == physics->brakes.driverValve->GetPos(bh_EB) - && physics->inductionMotor.braking.cylinderPressureGain < 0.001) - state.FzadED = 0; //pętla bezpieczeństwa - bez ED - state.FzadPN = state.Fzad - state.FrED * physics->brakes.blending.edForceFactor; -} -// steps 3-6 of the blending: the ED and the pneumatic braking forces set to the vehicles of the consist -void TDynamicObject::distributeBrakeForces( InductionBrakeState &state, double const dt1 ) -{ - std::vector PrzekrF( state.np ); - state.nPrzekrF = 0; - bool test = true; - std::vector FzED( state.np ); - std::vector FzEP( state.np ); - std::vector FmaxEP( state.np ); - // 3. ustaw pojazdom sile hamowania ED - // - proporcjonalnie do mozliwosci - - // 4. ustal potrzebne dohamowanie pneumatyczne - // - od sily zadanej trzeba odjac realizowana przez ED - // 5. w razie potrzeby wlacz hamulec utrzymujacy - // - gdy zahamowany ma ponizej 2 km/h - // 6. ustaw pojazdom sile hamowania ep - // - proporcjonalnie do masy, do liczby osi, rowne cisnienia - jak - // bedzie, tak bedzie dobrze - float Fpoj = 0; // physics->CabOccupied < 0 - ////ALGORYTM 2 - KAZDEMU PO ROWNO, ale nie wiecej niz eped * masa - // 1. najpierw daj kazdemu tyle samo - int i = 0; - for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; - p = state.kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) - { - auto const Nmax = ((p->physics->brakes.pressureToForce * p->physics->brakes.maxCylinderPressure[0] - - p->physics->brakes.cylinders.springForce) * - p->physics->brakes.cylinders.leverRatio[0] - - p->physics->brakes.cylinders.slackAdjusterForce) * - p->physics->brakes.cylinders.count * p->physics->brakes.cylinders.riggingEfficiency; - FmaxEP[i] = Nmax * - p->physics->brakes.distributor->GetFC( - Nmax / (p->physics->NAxles * p->physics->brakes.blocksPerAxle), - p->physics->brakes.blending.referenceSpeed) * - 1000; // sila hamowania pn - - PrzekrF[i] = false; - FzED[i] = state.FmaxED > 0 ? state.FzadED / state.FmaxED : 0; - p->physics->AnPos = - physics->ScndS ? state.LBR : FzED[i]; - FzEP[ i ] = static_cast( state.FzadPN * p->physics->NAxles ) / static_cast( state.osie ); - ++i; - p->physics->ShuntMode = physics->ShuntMode; - p->physics->ShuntModeAllow = physics->ShuntModeAllow; - } - while (test) - { - test = false; - i = 0; - float przek = 0; - for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; - p = state.kier == true ? p->Next(Coupling::control) : p->Prev(Coupling::control) ) - { - if (FzEP[i] > 0.01 && - FzEP[i] > p->physics->TotalMass * p->physics->inductionMotor.braking.maxEpDeceleration + std::min(p->physics->inductionMotor.state.maxForce, 0.) * 1000 && - !PrzekrF[i]) - { - float przek1 = -std::min(p->physics->inductionMotor.state.maxForce, 0.) * 1000 + - FzEP[i] - - p->physics->TotalMass * - p->physics->inductionMotor.braking.maxEpDeceleration * 0.999; - PrzekrF[i] = true; - test = true; - state.nPrzekrF++; - przek1 = std::min(przek1, FzEP[i]); - FzEP[i] -= przek1; - if (FzEP[i] < 0) - FzEP[i] = 0; - przek += przek1; - } - ++i; - } - i = 0; - przek = przek / (state.np - state.nPrzekrF); - for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; - true == state.kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) - { - if (!PrzekrF[i]) - { - FzEP[i] += przek; - } - ++i; - } - } - i = 0; - for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; - true == state.kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) - { - float Nmax = ((p->physics->brakes.pressureToForce * p->physics->brakes.maxCylinderPressure[0] - - p->physics->brakes.cylinders.springForce) * - p->physics->brakes.cylinders.leverRatio[0] - - p->physics->brakes.cylinders.slackAdjusterForce) * - p->physics->brakes.cylinders.count * p->physics->brakes.cylinders.riggingEfficiency; - if (state.FrED > 0.1) - p->physics->brakes.blending.epCorrectionTimer = 0; - else - p->physics->brakes.blending.epCorrectionTimer += dt1; - bool EPVC = p->physics->brakes.blending.epCorrection && (p->physics->brakes.blending.epCorrectionTime < 0 || p->physics->brakes.blending.epCorrectionTimer < p->physics->brakes.blending.epCorrectionTime); - float VelC = EPVC ? safe_clamp(p->physics->Vel, p->physics->brakes.blending.minSpeed, p->physics->brakes.blending.maxSpeed) : p->physics->brakes.blending.referenceSpeed;//korekcja EP po prędkości - float FmaxPoj = Nmax * - p->physics->brakes.distributor->GetFC( - Nmax / (p->physics->NAxles * p->physics->brakes.blocksPerAxle), VelC) * - 1000; // sila hamowania pn - p->physics->brakes.independentPositionEim = FzEP[i] / FmaxPoj; - if (p->physics->brakes.independentPositionEim>0.009) - if (p->physics->brakes.pressureToForce * p->physics->brakes.cylinders.leverRatio[0] * - p->physics->brakes.maxCylinderPressure[0] != 0) - { - float x = (p->physics->brakes.cylinders.slackAdjusterForce / p->physics->brakes.cylinders.leverRatio[0] + - p->physics->brakes.cylinders.springForce) / (p->physics->brakes.pressureToForce * - p->physics->brakes.maxCylinderPressure[0]); - p->physics->brakes.independentPositionEim = x + (1 - x) * p->physics->brakes.independentPositionEim; - } - else - p->physics->brakes.independentPositionEim = p->physics->brakes.independentPositionEim; - else - p->physics->brakes.independentPositionEim = 0; - if (p->physics->brakes.independentTraxx) - { - p->physics->eim_localbrake = state.eim_lb; - p->physics->brakes.independentPositionEim = std::max(p->physics->brakes.independentPositionEim, state.eim_lb); - } - ++i; - } -} - -// the state of the blending kept for the debug screen, and written to the log of the braking while it is open -void TDynamicObject::recordMedState( InductionBrakeState const &state, double const dt1 ) -{ - MED[0][0] = state.masa*0.001; - MED[0][1] = state.amax; - MED[0][2] = state.Fzad*0.001; - MED[0][3] = state.FmaxPN*0.001; - MED[0][4] = state.FmaxED*0.001; - MED[0][5] = state.FrED*0.001; - MED[0][6] = state.FzadPN*0.001; - MED[0][7] = state.nPrzekrF; - - if (MEDLogFile.is_open()) - { - MEDLogFile << MEDLogTime << "\t" << physics->Vel << "\t" << state.masa*0.001 << "\t" << state.osie << "\t" << state.FmaxPN*0.001 << "\t" << state.FmaxED*0.001 << "\t" - << state.FfulED*0.001 << "\t" << state.FrED*0.001 << "\t" << state.Fzad*0.001 << "\t" << state.FzadED*0.001 << "\t" << state.FzadPN*0.001; - for (TDynamicObject *p = GetFirstDynamic(physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); p; - true == state.kier ? p = p->Next(Coupling::control) : p = p->Prev(Coupling::control)) - { - MEDLogFile << "\t" << p->physics->brakes.cylinderPressure; - } - MEDLogFile << "\n"; - if (floor(MEDLogTime + dt1) > floor(MEDLogTime)) - { - MEDLogFile.flush(); - } - MEDLogTime += dt1; - - if (physics->Vel < 0.1 || physics->MainCtrlPowerPos() > 0) - { - MEDLogInactiveTime += dt1; - } - else - { - MEDLogInactiveTime = 0; - } - if (MEDLogInactiveTime > 5) - { - MEDLogFile.flush(); - MEDLogFile.close(); - } - + auto const forward { DirectionGet() * physics->CabOccupied > 0 }; + std::vector consist; + for( TDynamicObject *vehicle = GetFirstDynamic( physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control ); vehicle != nullptr; + vehicle = forward ? vehicle->Next( Coupling::control ) : vehicle->Prev( Coupling::control ) ) { + consist.emplace_back( vehicle->physics ); } + physics::ConsistBrakeBlending::Inputs inputs; + inputs.owner = ctOwner != nullptr ? ctOwner->Controlling() : nullptr; + inputs.aiDriving = Mechanik->AIControllFlag; + Mechanik->fMedAmax = brakeBlending.Update( *physics, consist, inputs, dt1 ); } // the main switch off, with the supply of the vehicle's circuits off, but for diesel engines and hand cars From 447fe54f3d682352e731a837812848c650372041 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 10:31:03 +0100 Subject: [PATCH 13/30] refactor(ai): the start uphill, the running brake test, the braking shortfall and the sanded start as named state What the AI keeps in mind about these was spread over loose members of TController, and their stages over flags and numbers: - the start uphill (bUphillStart, bUphillRelease, bUphillBrakeTopUp and five more) is uphill_start::Progress, its phases an enum (none, holding, releasing) the two flags could only approximate, with Begin(), Release() and End() where the flags were set together; - the running brake test of a train run (DynamicBrakeTest 0..5 and the DBT_* figures) is RunningBrakeTest, its stages named (waiting, applying, switchingToAir, measuring, releasing, done); the debug panel still shows the stage as the number it was; - the braking shortfall and the sanded start are small structs of their own. StaticBrakeTest, which nothing read or wrote, is gone. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- application/driveruipanels.cpp | 8 ++--- vehicle/Driver.h | 64 ++++++++++++++++++++++----------- vehicle/ai/consist.cpp | 15 +++----- vehicle/ai/controls.cpp | 4 +-- vehicle/ai/force.cpp | 66 ++++++++++++++++------------------ vehicle/ai/situation.cpp | 12 +++---- vehicle/ai/speed.cpp | 62 ++++++++++++++++---------------- vehicle/uphillstart.h | 40 +++++++++++++++++++++ 8 files changed, 160 insertions(+), 111 deletions(-) diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 8a333f4c4..999217132 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -1265,10 +1265,10 @@ debug_panel::update_section_ai( std::vector &Output ) const { + "\n activation threshold: " + to_string( mechanik.fAccThreshold, 2 ) + ", delays: " + to_string( mechanik.fBrake_a0[ 0 ], 2 ) + " + " + to_string( mechanik.fBrake_a1[ 0 ], 2 ) + "\n virtual brake position: " + to_string( mechanik.BrakeCtrlPosition, 2 ) - + "\n test stage: " + std::to_string( mechanik.DynamicBrakeTest ) - + ", applied at: " + to_string( mechanik.DBT_VelocityBrake, 0 ) - + ", release at: " + to_string( mechanik.DBT_VelocityRelease, 0 ) - + ", done at: " + to_string( mechanik.DBT_VelocityFinish, 0 ); + + "\n test stage: " + std::to_string( static_cast( mechanik.brakeTest.stage ) ) + + ", applied at: " + to_string( mechanik.brakeTest.velocityBrake, 0 ) + + ", release at: " + to_string( mechanik.brakeTest.velocityRelease, 0 ) + + ", done at: " + to_string( mechanik.brakeTest.velocityFinish, 0 ); Output.emplace_back( textline, Global.UITextColor ); diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 93d2260ba..9ed95141f 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -213,6 +213,45 @@ static const int gbh_MIN = -2; //minimalna pozycja w hamulcu ogolnym static const int gbh_MAX = 6; //maksymalna pozycja w hamulcu ogolnym //---------------------------------------------------------------------------- +// the running brake test of a train run (hamowanie kontrolne), as the timetable asks for it +struct RunningBrakeTest +{ + enum class Stage + { + waiting, // for the speed to run it at + applying, // the brake applied, the electropneumatic brake still in + switchingToAir, // the electropneumatic brake out, the train braked by the air brake alone + measuring, // braking down by 8 km/h, timed + releasing, // the brakes released + done + }; + Stage stage{ Stage::waiting }; + double velocityBrake{ 0.0 }; // where the braking began, then where its timed part began [km/h] + double velocityRelease{ 0.0 }; // the speed the brakes are released at [km/h] + double velocityFinish{ 0.0 }; // the speed the test ended at [km/h] + double brakingTime{ 0.0 }; // when the braking began, then how long its timed part took [s] + double releasingTime{ 0.0 }; // when the release began, then how long it took [s] + double midPointAcc{ 0.0 }; // the deceleration at the end of the timed part [m/s2] + + // the brakes applied by the test, until the release + bool IsBraking() const { return stage >= Stage::applying && stage <= Stage::measuring; } +}; + +// how far the train falls short of the braking it is asked for, as the driver watches it +struct BrakingShortfall +{ + double value{ 0.0 }; // at the last check [m/s2] + double time{ 0.0 }; // when that was checked + int growth{ 0 }; // how many checks in a row it has grown +}; + +// a start in which the wheels slipped: sand while under power until the train is under way +struct SandedStart +{ + bool active{ false }; + double decreaseTime{ -1.0 }; // when the power was last taken down a step for a slip +}; + class TController { // TBD: few authorized inspectors, or bunch of public getters? friend class TTrain; @@ -430,19 +469,9 @@ private: double fAccDesiredAv = 0.0; // uśrednione przyspieszenie z kolejnych przebłysków świadomości, żeby ograniczyć migotanie double fBrakeHeldTime = 0.0; // czas od ostatniego przestawienia kranu hamulca zasadniczego bool bStopTargetIsPassengerStop = false; // the point the train is to stop at, found by the last scan of the route, is a passenger stop - double fShortfall = 0.0; // how far the train fell short of the braking demand at the last check [m/s2] - 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 - uphill_start::top_up UphillTopUp; // starting uphill, what has been done to apply the train brake further - double fUphillReleaseTime = 0.0; // when the release began - double fUphillTractiveForce = 0.0; // the tractive force of the consist while starting uphill [N] - double fUphillHoldingForce = 0.0; // the grade force on the consist while starting uphill [N] + BrakingShortfall brakingShortfall; + uphill_start::Progress uphillStart; // a start uphill, the train brake holding the train until the power does + SandedStart sandedStart; 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 @@ -519,14 +548,7 @@ private: double DepartBlockedStart = -1.0; TBrakeSystem BrakeSystem = TBrakeSystem::Individual; //type of main brake bool ForcePNBrake = false; //is it necessary to use PN brake instead of EP brake - int DynamicBrakeTest = 0; //is it necessary to make brake test while driving - double DBT_VelocityBrake = 0; - double DBT_VelocityRelease = 0; - double DBT_VelocityFinish = 0; - double DBT_BrakingTime = 0; - double DBT_ReleasingTime = 0; - double DBT_MidPointAcc = 0; - int StaticBrakeTest = 0; //is it necessary to make brake test while standing + RunningBrakeTest brakeTest; double LastReactionTime = 0.0; double fActionTime = 0.0; // czas używany przy regulacji prędkości i zamykaniu drzwi double m_radiocontroltime{ 0.0 }; // timer used to control speed of radio operations diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index b5cd7e78a..507fca0b2 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -416,14 +416,7 @@ bool TController::CheckVehicles(DriverOrders user) // kasowanie pamieci hamowania kontrolnego if (OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::disconnect | DriverOrder::connect | DriverOrder::changeDirection)) { - DynamicBrakeTest = 0; - DBT_VelocityBrake - = DBT_VelocityRelease - = DBT_VelocityFinish - = DBT_BrakingTime - = DBT_ReleasingTime - = DBT_MidPointAcc - = 0; + brakeTest = {}; } if( brake_setting::inspects_train( OrderCurrentGet(), user == DriverOrder::connect ) ) { @@ -715,7 +708,7 @@ TController::determine_consist_state() { double dy; // składowa styczna grawitacji, w przedziale <0,1> // starting uphill the power is applied against the train brake on purpose, until the power holds the train and // then while the brake releases - auto const heldforstart { bUphillStart }; + auto const heldforstart { uphillStart.IsActive() }; 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 }; @@ -744,7 +737,7 @@ TController::determine_consist_state() { // ready all the same with the power going on against the brake on purpose: at a standstill, and once // the power holds the train, while the brake releases; otherwise in motion a braking force left // anywhere in the train (a hand brake) stops it as before - Ready = Ready && heldforstart && ( bUphillRelease || ( vehicle->Vel < 1.0 ) ); + Ready = Ready && heldforstart && ( uphillStart.IsReleasing() || ( vehicle->Vel < 1.0 ) ); } } if( wasready ) { @@ -765,7 +758,7 @@ TController::determine_consist_state() { } } // the brake held for the start counts again once it is being released - fReady = std::max( ( heldforstart && ( false == bUphillRelease ) ) ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego + fReady = std::max( ( heldforstart && ( false == uphillStart.IsReleasing() ) ) ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego if( ( dy = p->VectorFront().y ) != 0.0 ) { // istotne tylko dla pojazdów na pochyleniu // ciężar razy składowa styczna grawitacji diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index 0b9bc5cb6..0fb94ba1d 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -106,7 +106,7 @@ TController::increase_train_brake() { occupied->brakes.delays[ 1 ] : occupied->brakes.delays[ 3 ] ) // a train falling further behind needs no full fill time to be seen not to get enough - || ( ( fShortfall > 0.02 ) + || ( ( brakingShortfall.value > 0.02 ) && ( fBrakeHeldTime > vehicle_ai::brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) { // the table says the present position is enough, but the brake has had its full fill // time since the handle last moved and the train is still not slowing down as asked: @@ -336,7 +336,7 @@ bool TController::DecBrake() { // a position short of the first one brakes no weaker than that deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * std::max( 0.0, BrakeCtrlPosition - pos_diff ) * fBrake_a1[ 0 ] ); } - if( bUphillStart && ( false == bUphillRelease ) ) { + if( uphillStart.IsHolding() ) { // starting uphill the train brake holds the train until the power does break; } diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp index b8cc3c823..aeae777f5 100644 --- a/vehicle/ai/force.cpp +++ b/vehicle/ai/force.cpp @@ -151,9 +151,9 @@ void TController::control_tractive_force() { && (AbsAccS < AccDesired /*- std::min( 0.05, 0.01 * iDriverFailCount )*/ || occupied->SpeedCtrlUnit.IsActive && velocity < occupied->SpeedCtrlUnit.FullPowerVelocity) && false == drivingFlags.press && // starting uphill against the releasing brake, no more power than holds the train - uphill_start::may_add_power( bUphillRelease, fUphillTractiveForce, fUphillHoldingForce ) && + uphill_start::may_add_power( uphillStart.IsReleasing(), uphillStart.tractiveForce, uphillStart.holdingForce ) && // nor while the train brake is still being applied further to hold the train - false == bUphillBrakeTopUp && + false == uphillStart.toppingUp && velocity < (VelDesired == 1.0 ? // work around for trains getting stuck on tracks with speed limit = 1 VelDesired : VelDesired - fVelMinus) && @@ -213,12 +213,12 @@ void TController::control_uphill_start() { end_uphill_start(); return; } - fUphillTractiveForce = 0.0; + uphillStart.tractiveForce = 0.0; for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { // Ft is signed in the vehicle's own frame, and turned into the direction of travel as AbsAccS is - fUphillTractiveForce += std::max( 0.0, vehicle->physics->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); + uphillStart.tractiveForce += std::max( 0.0, vehicle->physics->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); } - fUphillHoldingForce = fMass * -fAccGravity; + uphillStart.holdingForce = fMass * -fAccGravity; uphill_start::situation const now { .standing = std::abs( velocity ) < EU07_AI_NOMOVEMENT, .velocity = velocity, @@ -226,18 +226,15 @@ void TController::control_uphill_start() { .speed_up = AccDesired > EU07_AI_NOACCELERATION, .speed_asked = VelDesired > 0.0, .train_brake_applied = BrakeCtrlPosition > 0.0, - .tractive_force = fUphillTractiveForce, - .grade_force = fUphillHoldingForce, + .tractive_force = uphillStart.tractiveForce, + .grade_force = uphillStart.holdingForce, .consist_released = IsConsistReleased, .consist_charged = IsConsistCharged }; - if( false == bUphillStart ) { + if( false == uphillStart.IsActive() ) { if( false == uphill_start::begins( now ) ) { return; } - bUphillStart = true; - bUphillRelease = false; - UphillTopUp = {}; - fUphillStartTime = ElapsedTime; + uphillStart.Begin( ElapsedTime ); } if( false == now.speed_up ) { // no longer to start: the standing rules take over @@ -249,26 +246,25 @@ void TController::control_uphill_start() { end_uphill_start(); return; } - bUphillBrakeTopUp = false; - if( false == bUphillRelease ) { - bUphillBrakeTopUp = uphill_brake_top_up(); - if( bUphillBrakeTopUp ) { + uphillStart.toppingUp = false; + if( false == uphillStart.IsReleasing() ) { + uphillStart.toppingUp = uphill_brake_top_up(); + if( uphillStart.toppingUp ) { return; } if( ( occupied->brakes.localKind != TLocalBrake::ManualBrake ) && ( occupied->brakes.independentPosition > 0.0 ) ) { cue_action( driver_hint::independentbrakerelease ); } - if( uphill_start::power_holds( now, ElapsedTime - fUphillStartTime ) ) { + if( uphill_start::power_holds( now, ElapsedTime - uphillStart.startTime ) ) { // the power holds the train: the train brake can be released - bUphillRelease = true; - fUphillReleaseTime = ElapsedTime; + uphillStart.Release( ElapsedTime ); } return; } // the train brake is being released with the power on. the start ends once the brakes are off: ended before, // the brake still on takes the power off, the train rolls back and has to be braked to a stand again - if( uphill_start::released( now, ElapsedTime - fUphillReleaseTime ) ) { + if( uphill_start::released( now, ElapsedTime - uphillStart.releaseTime ) ) { end_uphill_start(); } } @@ -290,13 +286,13 @@ bool TController::uphill_brake_top_up() { return false; } auto const action { uphill_start::brake_top_up( - UphillTopUp, trainbrakeforce, fUphillHoldingForce, BrakeCtrlPosition, fBrakeHeldTime, + uphillStart.brakeTopUp, trainbrakeforce, uphillStart.holdingForce, BrakeCtrlPosition, fBrakeHeldTime, occupied->brakes.delays[ occupied->brakes.delaySetting > bdelay_G ? 1 : 3 ] ) }; if( action == uphill_start::top_up_action::none ) { return false; } // the time for the power to hold the train starts once the brake does - fUphillStartTime = ElapsedTime; + uphillStart.startTime = ElapsedTime; if( action == uphill_start::top_up_action::step ) { BrakeLevelAdd( BrakingLevelIncrease ); } @@ -305,9 +301,7 @@ bool TController::uphill_brake_top_up() { void TController::end_uphill_start() { - bUphillStart = false; - bUphillRelease = false; - bUphillBrakeTopUp = false; + uphillStart.End(); } // standing, a train is prepared as a driver does it: the locomotive brake first, then the brake pipe is filled. the pipe @@ -435,7 +429,7 @@ void TController::control_braking_force() { auto const slippingbackuphill { ( fAccGravity < -0.05 ) && ( std::min( velocity, fConsistVelocity ) < -0.1 ) - && ( false == bUphillStart ) }; + && ( false == uphillStart.IsActive() ) }; // jeśli przyspieszamy, to nie hamujemy if( AccDesired > 0.0 && OrderCurrentGet() != DriverOrder::disconnect // przy odłączaniu nie zwalniamy tu hamulca @@ -451,14 +445,14 @@ void TController::control_braking_force() { // every few seconds, note how far the train falls short of the demand and whether that is getting worse: a brake // still filling, or blocks gripping harder as the train slows down, make up a shortfall on their own, but a // shortfall that keeps growing at a constant handle means the train is falling further behind its braking curve - if( ElapsedTime - fShortfallTime >= 3.0 ) { + if( ElapsedTime - brakingShortfall.time >= 3.0 ) { auto const shortfall { AbsAccS - accdesiredresultant }; - iShortfallGrowth = ( - ( ( AccDesired < 0.0 ) && ( shortfall > fShortfall + 0.005 ) ) ? - iShortfallGrowth + 1 : + brakingShortfall.growth = ( + ( ( AccDesired < 0.0 ) && ( shortfall > brakingShortfall.value + 0.005 ) ) ? + brakingShortfall.growth + 1 : 0 ); - fShortfall = shortfall; - fShortfallTime = ElapsedTime; + brakingShortfall.value = shortfall; + brakingShortfall.time = ElapsedTime; } if( is_emu() && !ForcePNBrake ) { @@ -510,14 +504,14 @@ void TController::control_braking_force() { else if( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( AccDesired < 0.0 ) && ( BrakeCtrlPosition > 0.0 ) - && ( fShortfall > 0.02 ) - && ( iShortfallGrowth >= 2 ) + && ( brakingShortfall.value > 0.02 ) + && ( brakingShortfall.growth >= 2 ) && ( fBrakeHeldTime > vehicle_ai::brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) { // the train has been falling further behind the demand for a while at a handle left alone for longer than // the brake takes to respond: a small step now, while it still is small, rather than the deep one the // margin above would allow only once the train is far behind cue_action( driver_hint::brakingforceincrease ); - iShortfallGrowth = 0; + brakingShortfall.growth = 0; } if ( (accdesiredresultant < fAccGravity - 0.05 || AccDesired >= EU07_AI_NOACCELERATION) // no braking asked for, yet the train is slowing down more than that @@ -607,7 +601,7 @@ void TController::control_releaser() { state.cylinder_pressure = occupied->brakes.cylinderPressure; state.control_pressure = occupied->brakes.distributor->GetCRP(); state.velocity = occupied->Vel; - state.uphill_start = bUphillStart; + state.uphill_start = uphillStart.IsActive(); state.pressing = drivingFlags.press; // stage 3 of uncoupling (UpdateDisconnect), from the direction change until the coupler lets go state.compressing_buffers = diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index d51431ecc..267671e4a 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -103,30 +103,30 @@ TController::control_wheelslip() { && velocity < EU07_AI_SANDEDSTARTVELOCITY && false == mvControlling->IsMainCtrlNoPowerPos() && mvControlling->Sand > 0.0 ) { - bSandedStart = true; + sandedStart.active = true; } else if( velocity >= EU07_AI_SANDEDSTARTVELOCITY || ( velocity < EU07_AI_NOMOVEMENT && VelDesired == 0.0 ) ) { - bSandedStart = false; + sandedStart.active = false; } // wheel slip if( mvControlling->SlippingWheels ) { cue_action( driver_hint::sandingon ); // piasku! - if( false == bSandedStart ) { + if( false == sandedStart.active ) { cue_action( driver_hint::tractiveforcedecrease ); cue_action( driver_hint::antislip ); } - else if( ElapsedTime - fSandedStartDecreaseTime >= 1.0 ) { + else if( ElapsedTime - sandedStart.decreaseTime >= 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; + sandedStart.decreaseTime = ElapsedTime; } cue_action( driver_hint::brakingforcedecrease ); ++iDriverFailCount; } else if( ( std::fabs( mvControlling->Im ) > 0.75 * mvControlling->ImaxHi ) - || ( bSandedStart && false == mvControlling->IsMainCtrlNoPowerPos() ) ) { + || ( sandedStart.active && false == mvControlling->IsMainCtrlNoPowerPos() ) ) { cue_action( driver_hint::sandingon ); // piaskujemy tory, coby się nie ślizgać } else { diff --git a/vehicle/ai/speed.cpp b/vehicle/ai/speed.cpp index 55b8db7f0..36f13e427 100644 --- a/vehicle/ai/speed.cpp +++ b/vehicle/ai/speed.cpp @@ -817,8 +817,8 @@ void TController::adjust_desired_speed_for_braking_test() { // if( false == Global.DynamicBrakeTest ) { return; } - if( DynamicBrakeTest >= 5 ) { return; } // all done - if( ( DynamicBrakeTest == 0 ) + if( brakeTest.stage == RunningBrakeTest::Stage::done ) { return; } + if( ( brakeTest.stage == RunningBrakeTest::Stage::waiting ) && ( 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( occupied->brakes.driverValveType == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now @@ -831,64 +831,65 @@ TController::adjust_desired_speed_for_braking_test() { auto const routeaccdesiredgravity { fAccDesiredGravity }; auto const routeveldesired { VelDesired }; - switch( DynamicBrakeTest ) { - case 0: { + using enum RunningBrakeTest::Stage; + switch( brakeTest.stage ) { + case waiting: { if( primary() && vel < VelDesired && fAccGravity >= 0.0 // not if going uphill && AccDesired >= EU07_AI_ACCELERATION && TrainParams.TTVmax >= 10.0 && vel > std::min(TrainParams.TTVmax, 60.0) - 2.0 ) { - DynamicBrakeTest = 1; - DBT_BrakingTime = ElapsedTime; - DBT_VelocityBrake = vel; + brakeTest.stage = applying; + brakeTest.brakingTime = ElapsedTime; + brakeTest.velocityBrake = vel; } break; } - case 1: { + case applying: { AccDesired = EU07_AI_BRAKINGTESTACCELERATION; fAccDesiredGravity = 0.0; - VelDesired = DBT_VelocityBrake; - if( ElapsedTime - DBT_BrakingTime > 1 ) { + VelDesired = brakeTest.velocityBrake; + if( ElapsedTime - brakeTest.brakingTime > 1 ) { ForcePNBrake = true; occupied->EpFuseSwitch( false ); - DynamicBrakeTest = 2; + brakeTest.stage = switchingToAir; } break; } - case 2: { + case switchingToAir: { AccDesired = EU07_AI_BRAKINGTESTACCELERATION; fAccDesiredGravity = 0.0; - VelDesired = DBT_VelocityBrake; - if( ElapsedTime - DBT_BrakingTime > 2 ) { - DBT_BrakingTime = ElapsedTime; - DBT_VelocityBrake = vel; - DBT_VelocityRelease = vel - 8.0; - DynamicBrakeTest = 3; + VelDesired = brakeTest.velocityBrake; + if( ElapsedTime - brakeTest.brakingTime > 2 ) { + brakeTest.brakingTime = ElapsedTime; + brakeTest.velocityBrake = vel; + brakeTest.velocityRelease = vel - 8.0; + brakeTest.stage = measuring; } break; } - case 3: { + case measuring: { AccDesired = safe_clamp( -AbsAccS, fAccThreshold * 1.01, fAccThreshold * 1.21 ); fAccDesiredGravity = 0.0; - VelDesired = DBT_VelocityBrake; - if( vel <= DBT_VelocityRelease ) { - DynamicBrakeTest = 4; - DBT_BrakingTime = ElapsedTime - DBT_BrakingTime; - DBT_MidPointAcc = AbsAccS; - DBT_ReleasingTime = ElapsedTime; + VelDesired = brakeTest.velocityBrake; + if( vel <= brakeTest.velocityRelease ) { + brakeTest.stage = releasing; + brakeTest.brakingTime = ElapsedTime - brakeTest.brakingTime; + brakeTest.midPointAcc = AbsAccS; + brakeTest.releasingTime = ElapsedTime; } break; } - case 4: { + case releasing: { if( Ready ) { if( BrakeSystem == TBrakeSystem::ElectroPneumatic ) { occupied->EpFuseSwitch( true ); } ForcePNBrake = false; - DynamicBrakeTest = 5; - DBT_ReleasingTime = ElapsedTime - DBT_ReleasingTime; - DBT_VelocityFinish = vel; + brakeTest.stage = done; + brakeTest.releasingTime = ElapsedTime - brakeTest.releasingTime; + brakeTest.velocityFinish = vel; } break; } @@ -897,8 +898,7 @@ TController::adjust_desired_speed_for_braking_test() { } } // a stop or a restriction coming up while the test runs takes precedence - if( ( DynamicBrakeTest >= 1 ) - && ( DynamicBrakeTest <= 3 ) + if( brakeTest.IsBraking() && ( routeaccdesired < AccDesired ) ) { AccDesired = routeaccdesired; fAccDesiredGravity = routeaccdesiredgravity; diff --git a/vehicle/uphillstart.h b/vehicle/uphillstart.h index 687934990..e50876588 100644 --- a/vehicle/uphillstart.h +++ b/vehicle/uphillstart.h @@ -62,6 +62,46 @@ struct top_up { bool done{false}; // a step added next to nothing: no more of them in this start }; +// where a start has got to +enum class Phase { + none, // no start uphill + holding, // the train brake holds the train until the power does + releasing // the power holds the train and the train brake is being released +}; + +// the start uphill as the driver keeps it in mind +struct Progress { + Phase phase{Phase::none}; + bool toppingUp{false}; // in this step the train brake is applied further, before the locomotive brake comes off + top_up brakeTopUp; // what has been done to apply the train brake further + double startTime{0.0}; // when the start began, or the train brake last held the train [s] + double releaseTime{0.0}; // when the release began [s] + double tractiveForce{0.0}; // of the consist, in the direction of travel [N] + double holdingForce{0.0}; // the grade force on the consist [N] + + bool IsActive() const { return phase != Phase::none; } + bool IsHolding() const { return phase == Phase::holding; } + bool IsReleasing() const { return phase == Phase::releasing; } + // the start begins at the given time, the train brake holding the train + void Begin(double const Time) + { + phase = Phase::holding; + brakeTopUp = {}; + startTime = Time; + } + // the power holds the train from the given time, the train brake is released + void Release(double const Time) + { + phase = Phase::releasing; + releaseTime = Time; + } + void End() + { + phase = Phase::none; + toppingUp = false; + } +}; + enum class top_up_action { none, // the brake holds the train, or can't be made to: the start goes on wait, // the cylinders are still filling after the last step From 2d67e9b1a3f783dff79ea2f1ef32e801c08465ef Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 10:36:09 +0100 Subject: [PATCH 14/30] refactor(physics): the definition of the brakes apart from their state What the .fiz gives about the brakes of a vehicle (the kinds of the brake system, the valves and the handles, the cylinders and the rigging, the pipe pressures, the delays and the modes it can be set to: 35 fields) moves into physics::Braking::Config, held as brakes.config, set as the vehicle loads and not changed after. Six fields that sat with the definition but change in the run (the weighted pressures of the handle position, the universal buttons pressed, the load setting, the control reservoir, the emergency valve, the lock of the pipe) go with the state. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- application/driverhints.cpp | 8 +- physics/components/body.cpp | 72 +++++++------- physics/components/braking.h | 88 +++++++++-------- physics/components/cab.cpp | 2 +- physics/components/commands.cpp | 2 +- physics/components/controllers.cpp | 10 +- physics/components/fizparser.cpp | 28 +++--- physics/components/fizsections.cpp | 134 +++++++++++++------------- physics/components/pneumatics.cpp | 112 ++++++++++----------- physics/components/securitysystem.cpp | 2 +- physics/components/setup.cpp | 120 +++++++++++------------ physics/components/traction.cpp | 10 +- physics/consistbraking.cpp | 60 ++++++------ physics/vehicle.h | 2 +- tests/unit/golden.cpp | 60 ++++++------ tests/unit/invariants.cpp | 4 +- tests/unit/test_brake_cycle.cpp | 2 +- tests/unit/test_brake_handles.cpp | 8 +- tests/unit/test_brake_pipe.cpp | 6 +- tests/unit/test_brakes.cpp | 2 +- tests/unit/test_cntrl.cpp | 6 +- tests/unit/test_crew.cpp | 2 +- tests/unit/test_definition.cpp | 6 +- tests/unit/test_drivingaid.cpp | 2 +- tests/unit/test_elf_controller.cpp | 6 +- tests/unit/test_est3al2_relay.cpp | 2 +- tests/unit/test_fiz.cpp | 2 +- tests/unit/vehicle.cpp | 2 +- vehicle/ai/consist.cpp | 18 ++-- vehicle/ai/controls.cpp | 28 +++--- vehicle/ai/driver.cpp | 2 +- vehicle/ai/engine.cpp | 8 +- vehicle/ai/force.cpp | 42 ++++---- vehicle/ai/speed.cpp | 6 +- vehicle/brakesetting.cpp | 2 +- vehicle/cab/brakecommands.cpp | 42 ++++---- vehicle/cab/sounds.cpp | 6 +- vehicle/cab/train.cpp | 4 +- vehicle/cab/update.cpp | 12 +-- vehicle/crew.cpp | 4 +- vehicle/dynamic/lifecycle.cpp | 16 +-- vehicle/dynamic/sounds.cpp | 16 +-- 42 files changed, 485 insertions(+), 481 deletions(-) diff --git a/application/driverhints.cpp b/application/driverhints.cpp index d84e663df..b3ba49897 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -490,7 +490,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this]( float const /*Parameter*/ ) { - return occupied->brakes.localKind != TLocalBrake::ManualBrake || occupied->brakes.hasHandBrake == false || occupied->brakes.handBrakePosition == ManualBrakePosNo; } ); + return occupied->brakes.config.localKind != TLocalBrake::ManualBrake || occupied->brakes.config.hasHandBrake == false || occupied->brakes.handBrakePosition == ManualBrakePosNo; } ); break; } case driver_hint::manualbrakoff: { @@ -501,7 +501,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this]( float const /*Parameter*/ ) { - return occupied->brakes.localKind != TLocalBrake::ManualBrake || occupied->brakes.hasHandBrake == false || occupied->brakes.handBrakePosition == 0; } ); + return occupied->brakes.config.localKind != TLocalBrake::ManualBrake || occupied->brakes.config.hasHandBrake == false || occupied->brakes.handBrakePosition == 0; } ); break; } // master controller @@ -818,7 +818,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return is_equal(occupied->brakes.handlePositionSmooth, occupied->brakes.driverValve->GetPos(bh_RP), 0.2) || (occupied->brakes.driverValve->Time && occupied->brakes.driverValve->GetCP() > occupied->brakes.pipeHighPressure - 0.05); } ); + return is_equal(occupied->brakes.handlePositionSmooth, occupied->brakes.driverValve->GetPos(bh_RP), 0.2) || (occupied->brakes.driverValve->Time && occupied->brakes.driverValve->GetCP() > occupied->brakes.config.pipeHighPressure - 0.05); } ); // return ( BrakeCtrlPosition == gbh_RP ); } ); break; } @@ -1001,7 +1001,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvControlling->brakes.antiSlipType != 1 || (mvControlling->brakes.distributor->GetBrakeStatus() & b_asb) != 0 || mvControlling->SlippingWheels == false; } ); + return mvControlling->brakes.config.antiSlipType != 1 || (mvControlling->brakes.distributor->GetBrakeStatus() & b_asb) != 0 || mvControlling->SlippingWheels == false; } ); break; } // horns diff --git a/physics/components/body.cpp b/physics/components/body.cpp index aa1d84224..084cf703d 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -101,17 +101,17 @@ physics::Vehicle::Vehicle(double VelInitial, std::string const &TypeNameInit, st for (int b = -1; b <= MainBrakeMaxPos; ++b) { - brakes.pressureTable[b].PipePressureVal = 0.0; - brakes.pressureTable[b].BrakePressureVal = 0.0; - brakes.pressureTable[b].FlowSpeedVal = 0.0; + brakes.config.pressureTable[b].PipePressureVal = 0.0; + brakes.config.pressureTable[b].BrakePressureVal = 0.0; + brakes.config.pressureTable[b].FlowSpeedVal = 0.0; } // with BrakePressureTable[-2] do {pozycja odciecia} { - brakes.pressureTable[-2].PipePressureVal = -1.0; - brakes.pressureTable[-2].BrakePressureVal = -1.0; - brakes.pressureTable[-2].FlowSpeedVal = 0.0; + brakes.config.pressureTable[-2].PipePressureVal = -1.0; + brakes.config.pressureTable[-2].BrakePressureVal = -1.0; + brakes.config.pressureTable[-2].FlowSpeedVal = 0.0; } - for (auto &delay : brakes.delays) + for (auto &delay : brakes.config.delays) { delay = 0.0; } @@ -126,7 +126,7 @@ physics::Vehicle::Vehicle(double VelInitial, std::string const &TypeNameInit, st Couplers[b].DmaxC = 0.1; Couplers[b].FmaxC = 1000.0; } - for (auto &cylindermult : brakes.cylinders.leverRatio) + for (auto &cylindermult : brakes.config.cylinders.leverRatio) { cylindermult = 0.0; } @@ -143,7 +143,7 @@ physics::Vehicle::Vehicle(double VelInitial, std::string const &TypeNameInit, st couplerentry.CheckCollision = false; } - for (auto &brakepress : brakes.maxCylinderPressure) + for (auto &brakepress : brakes.config.maxCylinderPressure) { brakepress = 0.0; } @@ -504,7 +504,7 @@ void physics::Vehicle::compute_movement_(double const Deltatime) brakes.electrodynamic.emuWorking &= Couplers[VehicleEnd::rear].Connected->brakes.electrodynamic.emuWorking; } - if (brakes.antiSlipTimer > 0.8 && brakes.antiSlipType != 128) + if (brakes.antiSlipTimer > 0.8 && brakes.config.antiSlipType != 128) { // ASBSpeed=0.8 // hamulec antypoślizgowy - wyłączanie brakes.distributor->ASB(0); @@ -834,11 +834,11 @@ void physics::Vehicle::ComputeTotalForce(double dt) double old_nrot = abs(nrot); nrot = v2n(); // przeliczenie prędkości liniowej na obrotową - if (true == TestFlag(brakes.method, bp_MHS) && brakePipe.Pressure() < 3.0 // ustawione na sztywno na 3 bar + if (true == TestFlag(brakes.config.method, bp_MHS) && brakePipe.Pressure() < 3.0 // ustawione na sztywno na 3 bar && Vel > 45 && true == TestFlag(brakes.delaySetting, bdelay_M)) { // doliczenie hamowania hamulcem szynowym - FStand += brakes.trackBrakeForce; + FStand += brakes.config.trackBrakeForce; } // w charakterystykach jest wartość siły hamowania zamiast nacisku @@ -942,22 +942,22 @@ double physics::Vehicle::BrakeForceR(double ratio, double velocity) const { double press = 0; ratio = brakes.distributor->GetBrakeRatio(ratio); - if (brakes.maxPressureMass > 2) + if (brakes.config.maxPressureMass > 2) { - press = brakes.maxCylinderPressure[1] + (brakes.maxCylinderPressure[3] - brakes.maxCylinderPressure[1]) * std::min(1.0, (TotalMass - Mass) / (brakes.maxPressureMass - Mass)); + press = brakes.config.maxCylinderPressure[1] + (brakes.config.maxCylinderPressure[3] - brakes.config.maxCylinderPressure[1]) * std::min(1.0, (TotalMass - Mass) / (brakes.config.maxPressureMass - Mass)); } else { - if (brakes.maxCylinderPressure[1] > 0.1) + if (brakes.config.maxCylinderPressure[1] > 0.1) { - press = brakes.maxCylinderPressure[brakes.loadSetting]; + press = brakes.config.maxCylinderPressure[brakes.loadSetting]; } else { - press = brakes.maxCylinderPressure[3]; + press = brakes.config.maxCylinderPressure[3]; if (brakes.electrodynamic.type == dbrake_automatic) ratio = ratio + (1.5 - ratio) * std::min(1.0, Vel * 0.02); - if (brakes.delaySetting & bdelay_R && brakes.method % 128 != bp_Cosid && brakes.method % 128 != bp_D1 && brakes.method % 128 != bp_D2 && Power < 1) + if (brakes.delaySetting & bdelay_R && brakes.config.method % 128 != bp_Cosid && brakes.config.method % 128 != bp_D1 && brakes.config.method % 128 != bp_D2 && Power < 1) ratio *= brakes.distributor->GetRapidRatio(velocity); if (TrainType == train_type::dmu && velocity < 30.0) { @@ -971,9 +971,9 @@ double physics::Vehicle::BrakeForceR(double ratio, double velocity) const double physics::Vehicle::BrakeForceP(double press, double velocity) const { double BFP = 0; - double K = ((press * brakes.pressureToForce - brakes.cylinders.springForce) * brakes.cylinders.leverRatio[0] - brakes.cylinders.slackAdjusterForce) * brakes.cylinders.riggingEfficiency; - K *= static_cast(brakes.cylinders.count) / (NAxles * std::max(1, brakes.blocksPerAxle)); - BFP = brakes.distributor->GetFC(velocity, K) * K * (NAxles * std::max(1, brakes.blocksPerAxle)) * 1000; + double K = ((press * brakes.config.pressureToForce - brakes.config.cylinders.springForce) * brakes.config.cylinders.leverRatio[0] - brakes.config.cylinders.slackAdjusterForce) * brakes.config.cylinders.riggingEfficiency; + K *= static_cast(brakes.config.cylinders.count) / (NAxles * std::max(1, brakes.config.blocksPerAxle)); + BFP = brakes.distributor->GetFC(velocity, K) * K * (NAxles * std::max(1, brakes.config.blocksPerAxle)) * 1000; return BFP; } @@ -987,16 +987,16 @@ double physics::Vehicle::BrakeForce(TTrackParam const & /*Track*/) double K{0}; double brakeforce{0}; - switch (brakes.localKind) + switch (brakes.config.localKind) { case TLocalBrake::ManualBrake: { - K = brakes.maxForce * ManualBrakeRatio(); + K = brakes.config.maxForce * ManualBrakeRatio(); break; } case TLocalBrake::HydraulicBrake: { - K = brakes.maxForce * LocalBrakeRatio(); + K = brakes.config.maxForce * LocalBrakeRatio(); break; } default: @@ -1005,34 +1005,34 @@ double physics::Vehicle::BrakeForce(TTrackParam const & /*Track*/) } } - if (brakes.hasHandBrake == true) + if (brakes.config.hasHandBrake == true) { - K = brakes.maxForce * ManualBrakeRatio(); + K = brakes.config.maxForce * ManualBrakeRatio(); } // the spring brake of a vehicle prepared for hauling (PulleeMode) is released by hand: no force, whatever its cylinder has if (brakes.spring.isReady && false == PulleeMode) K += std::max(0.0, brakes.spring.minForcePressure - brakes.spring.cylinder->P()) * brakes.spring.maxForce; - u = (brakes.cylinderPressure * brakes.pressureToForce - brakes.cylinders.springForce) * brakes.cylinders.leverRatio[0] - brakes.cylinders.slackAdjusterForce; - if (u * brakes.cylinders.riggingEfficiency > Ntotal) // histereza na nacisku klockow - Ntotal = u * brakes.cylinders.riggingEfficiency; + u = (brakes.cylinderPressure * brakes.config.pressureToForce - brakes.config.cylinders.springForce) * brakes.config.cylinders.leverRatio[0] - brakes.config.cylinders.slackAdjusterForce; + if (u * brakes.config.cylinders.riggingEfficiency > Ntotal) // histereza na nacisku klockow + Ntotal = u * brakes.config.cylinders.riggingEfficiency; else { - u = (brakes.cylinderPressure * brakes.pressureToForce - brakes.cylinders.springForce) * brakes.cylinders.leverRatio[0] - brakes.cylinders.slackAdjusterForce; - if (u * (2.0 - brakes.cylinders.riggingEfficiency) < Ntotal) // histereza na nacisku klockow - Ntotal = u * (2.0 - brakes.cylinders.riggingEfficiency); + u = (brakes.cylinderPressure * brakes.config.pressureToForce - brakes.config.cylinders.springForce) * brakes.config.cylinders.leverRatio[0] - brakes.config.cylinders.slackAdjusterForce; + if (u * (2.0 - brakes.config.cylinders.riggingEfficiency) < Ntotal) // histereza na nacisku klockow + Ntotal = u * (2.0 - brakes.config.cylinders.riggingEfficiency); } auto const NBrakeAxles{NAxles}; - if (NBrakeAxles * brakes.blocksPerAxle > 0) + if (NBrakeAxles * brakes.config.blocksPerAxle > 0) { if (Ntotal > 0) // nie luz K += Ntotal; // w kN - K *= static_cast(brakes.cylinders.count) / (NBrakeAxles * static_cast(brakes.blocksPerAxle)); // w kN na os + K *= static_cast(brakes.config.cylinders.count) / (NBrakeAxles * static_cast(brakes.config.blocksPerAxle)); // w kN na os } - if (brakes.kind == TBrakeSystem::Pneumatic || brakes.kind == TBrakeSystem::ElectroPneumatic) + if (brakes.config.kind == TBrakeSystem::Pneumatic || brakes.config.kind == TBrakeSystem::ElectroPneumatic) { u = brakes.distributor->GetFC(Vel, K); brakes.unitForce = u * K * 1000.0; // sila na jeden klocek w N @@ -1043,7 +1043,7 @@ double physics::Vehicle::BrakeForce(TTrackParam const & /*Track*/) // Fb:=UnitBrakeForce*NBpA {ham. reczny dziala na jedna os} // else //yB: to nie do konca ma sens, ponieważ ręczny w wagonie działa na jeden cylinder // hamulcowy/wózek, dlatego potrzebne są oddzielnie liczone osie - brakeforce = brakes.unitForce * NBrakeAxles * std::max(1, brakes.blocksPerAxle); + brakeforce = brakes.unitForce * NBrakeAxles * std::max(1, brakes.config.blocksPerAxle); // u:=((BrakePress*P2FTrans)-BrakeCylSpring*BrakeCylMult[BCMFlag]/BrakeCylNo-0.83*BrakeSlckAdj/(BrakeCylNo))*BrakeCylNo; // { end; } diff --git a/physics/components/braking.h b/physics/components/braking.h index 817403f9c..9aeb5f5ab 100644 --- a/physics/components/braking.h +++ b/physics/components/braking.h @@ -164,48 +164,54 @@ struct Braking std::shared_ptr driverValve; // the driver's brake valve of the train brake std::shared_ptr independentValve; // the driver's valve of the independent brake - // the definition - TBrakeSystem kind = TBrakeSystem::Individual; // the kind of the train brake - TBrakeSubSystem subsystem = TBrakeSubSystem::ss_None; - TBrakeValve distributorType = TBrakeValve::NoValve; - int distributorSize = 0; - std::string distributorParameters; - TBrakeHandle driverValveType = TBrakeHandle::NoHandle; - TBrakeHandle independentValveType = TBrakeHandle::NoHandle; - bool independentTraxx = false; // the independent brake of the Traxx kind - DriverValveSettings driverValveSettings; - TLocalBrake localKind = TLocalBrake::NoBrake; // the kind of the individual brake - TBrakePressureTable pressureTable; // the pressures in the pipe of the positions of the driver's valve - TBrakePressure actualPressure; // their values weighted for the present position of the valve - int antiSlipType = 0; // 0: no anti-slip brake, 1: by hand, 2: automatic - std::array universalButtonActions{}; // what the universal brake buttons do - std::array universalButtonPressed{}; // the universal brake buttons pressed - double maxForce = 0.0; // the most force of the brake - std::array maxCylinderPressure{}; // by the load setting: auxiliary, empty, medium, loaded, anti-slip - int loadSetting = 0; // the index of maxCylinderPressure the brake takes - double pressureToForce = 0.0; // P2FTrans - double trackBrakeForce = 0.0; // the force of the track brake - int method = 0; // the friction material and its flags (bp_*) - int blocksPerAxle = 0; // NBpA: 0, 1, 2 or 4 - double maxPressureMass = 1.0; // MBPM: the mass of the highest pressure - double pipeHighPressure = 0.0; // the highest working pressure of the brake pipe - double pipeLowPressure = 0.0; // the lowest one - double pipePressureRange = 0.0; // the difference between them - double controlReservoirPressure = 0.0; // the pressure in the control reservoir - double cylinderVolume = 0.0; // the volume of the brake cylinders - double valveVolume = 0.0; // BVV - BrakeCylinders cylinders; - double rapidRatio = 1.0; // the ratio of the rapid brake - double rapidSpeed = 55.0; // the speed the rapid brake switches at - double pipeSection = 0.0; // Spg: the cross-section of the brake pipe - EmergencyValve emergencyValve; - PipeLock pipeLock; - bool emergencyCutsOffDriverValve = false; // EmergencyCutsOffHandle - TBrakeDelayTable delays; // the delays of applying and releasing - int handlePositions = 0; // the positions of the driver's valve - bool hasHandBrake = false; + // the definition, what the .fiz gives: set as the vehicle loads, not changed after + struct Config + { + TBrakeSystem kind = TBrakeSystem::Individual; // the kind of the train brake + TBrakeSubSystem subsystem = TBrakeSubSystem::ss_None; + TBrakeValve distributorType = TBrakeValve::NoValve; + int distributorSize = 0; + std::string distributorParameters; + TBrakeHandle driverValveType = TBrakeHandle::NoHandle; + TBrakeHandle independentValveType = TBrakeHandle::NoHandle; + bool independentTraxx = false; // the independent brake of the Traxx kind + DriverValveSettings driverValveSettings; + TLocalBrake localKind = TLocalBrake::NoBrake; // the kind of the individual brake + TBrakePressureTable pressureTable; // the pressures in the pipe of the positions of the driver's valve + int antiSlipType = 0; // 0: no anti-slip brake, 1: by hand, 2: automatic + std::array universalButtonActions{}; // what the universal brake buttons do + double maxForce = 0.0; // the most force of the brake + std::array maxCylinderPressure{}; // by the load setting: auxiliary, empty, medium, loaded, anti-slip + double pressureToForce = 0.0; // P2FTrans + double trackBrakeForce = 0.0; // the force of the track brake + int method = 0; // the friction material and its flags (bp_*) + int blocksPerAxle = 0; // NBpA: 0, 1, 2 or 4 + double maxPressureMass = 1.0; // MBPM: the mass of the highest pressure + double pipeHighPressure = 0.0; // the highest working pressure of the brake pipe + double pipeLowPressure = 0.0; // the lowest one + double pipePressureRange = 0.0; // the difference between them + double cylinderVolume = 0.0; // the volume of the brake cylinders + double valveVolume = 0.0; // BVV + BrakeCylinders cylinders; + double rapidRatio = 1.0; // the ratio of the rapid brake + double rapidSpeed = 55.0; // the speed the rapid brake switches at + double pipeSection = 0.0; // Spg: the cross-section of the brake pipe + bool emergencyCutsOffDriverValve = false; // EmergencyCutsOffHandle + TBrakeDelayTable delays; // the delays of applying and releasing + int handlePositions = 0; // the positions of the driver's valve + bool hasHandBrake = false; + int availableDelays = 0; // the delays it can be set to + int availableOperatingModes = 0; + }; + Config config; // the state + TBrakePressure actualPressure; // their values weighted for the present position of the valve + std::array universalButtonPressed{}; // the universal brake buttons pressed + int loadSetting = 0; // the index of maxCylinderPressure the brake takes + double controlReservoirPressure = 0.0; // the pressure in the control reservoir + EmergencyValve emergencyValve; + PipeLock pipeLock; double cylinderPressure = 0.0; // the pressure in the brake cylinders double cylinderPressureRate = 0.0; // how fast it changes, averaged over about a second [bar/s], see accelerating() double independentCylinderPressure = 0.0; // the pressure in the cylinders from the independent brake @@ -227,12 +233,10 @@ struct Braking int status = 0; // the bits b_* (b_off 0, b_on, b_dmg, b_rls, b_asb, b_ep ...) bool alarmChain = false; // the manual emergency brake int delaySetting = 0; // the delay set (bdelay_*) - int availableDelays = 0; // the delays it can be set to // the AI wagon inspector cut the brake out (b_dmg) and puts it back when the train no longer needs it cut out // (brake_setting::apply). Anyone else cutting it out or putting it back takes it over bool cutOutByInspector = false; int operatingMode = 0; // the mode set (bom_*: PS/PN/EP/MED 1/2/4/8) - int availableOperatingModes = 0; double unitForce = 0.0; // the braking force of one braked element double antiSlipTimer = 0.0; // to switch the anti-slip brake off diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index 4ec0ad598..ca4313e8a 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -54,7 +54,7 @@ bool physics::Vehicle::ChangeCab(int direction) if (std::abs(CabOccupied + direction) < 2) { CabOccupied = CabOccupied + direction; - if (brakes.handlePositions > 0 && (brakes.kind == TBrakeSystem::Pneumatic || brakes.kind == TBrakeSystem::ElectroPneumatic)) + if (brakes.config.handlePositions > 0 && (brakes.config.kind == TBrakeSystem::Pneumatic || brakes.config.kind == TBrakeSystem::ElectroPneumatic)) { BrakeLevelSet(brakes.driverValve->GetPos(bh_NP)); brakes.pipeLimiterPressure = brakePipe.Pressure(); diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 44c87d814..68c3471e7 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -285,7 +285,7 @@ bool physics::Vehicle::RunBrakeCommand(VehicleCommand const Command, double CVal if (CValue1 < 0.001) brakes.electrodynamic.emuWorking = true; // fBrakeCtrlPos:=BrakeCtrlPos; //to powinnno być w jednym miejscu, aktualnie w C++!!! - brakes.actualPressure = brakes.pressureTable[brakes.handlePosition]; + brakes.actualPressure = brakes.config.pressureTable[brakes.handlePosition]; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } // youby - odluzniacz hamulcow, przyda sie else if (Command == VehicleCommand::brakeReleaser) diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index df91588b2..7dbc286c8 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -1025,7 +1025,7 @@ void physics::Vehicle::CheckEIMIC(double dt) EIMICFromUniversalController(dt, brakeDemand); break; } - if (brakes.independentTraxx) + if (brakes.config.independentTraxx) { EIMICTraxxLocalBrake(dt); } @@ -1041,7 +1041,7 @@ void physics::Vehicle::EIMICFromController(double const brakeDemand, double cons { if (eimic > 0.001) eimic = std::max(0.002, eimic * (double)MainCtrlPosNo / ((double)MainCtrlPosNo - offset) - offset / ((double)MainCtrlPosNo - offset)); - if (eimic < -0.001 && brakes.driverValveType != TBrakeHandle::MHZ_EN57) + if (eimic < -0.001 && brakes.config.driverValveType != TBrakeHandle::MHZ_EN57) eimic = std::min(-0.002, eimic * (double)LocalBrakePosNo / ((double)LocalBrakePosNo - multiplier) + offset / ((double)LocalBrakePosNo - multiplier)); } if (eimic > 0.001 && SpeedCtrlUnit.IsActive) @@ -1197,11 +1197,11 @@ void physics::Vehicle::EIMICTraxxLocalBrake(double dt) if (LocalBrakeRatio() > 0.6) // pozycja 2, zahamowywanie { eim_localbrake += dt * 0.17; - eim_localbrake = std::max(eim_localbrake, brakes.cylinderPressure / brakes.maxCylinderPressure[0]); + eim_localbrake = std::max(eim_localbrake, brakes.cylinderPressure / brakes.config.maxCylinderPressure[0]); } else // pozycja 1, utrzymanie cisnienia { - if (eim_localbrake < brakes.distributor->GetEDBCP() / brakes.maxCylinderPressure[0]) + if (eim_localbrake < brakes.distributor->GetEDBCP() / brakes.config.maxCylinderPressure[0]) eim_localbrake = 0; } eim_localbrake = std::clamp(eim_localbrake, 0.0, 1.0); @@ -1253,7 +1253,7 @@ void physics::Vehicle::CheckSpeedCtrl(double dt) { SpeedCtrlUnit.Standby = false; } - if (!SpeedCtrlUnit.BrakeIntervention && (brakes.distributor->GetEDBCP() > 0.4 || brakePipe.Pressure() < brakes.pipeHighPressure - 0.2)) + if (!SpeedCtrlUnit.BrakeIntervention && (brakes.distributor->GetEDBCP() > 0.4 || brakePipe.Pressure() < brakes.config.pipeHighPressure - 0.2)) SpeedCtrlUnit.Standby = true; if (EIMCtrlType >= 3 && UniCtrlList[MainCtrlPos].SpeedUp <= 0) { diff --git a/physics/components/fizparser.cpp b/physics/components/fizparser.cpp index debbeb149..d4dbda73a 100644 --- a/physics/components/fizparser.cpp +++ b/physics/components/fizparser.cpp @@ -231,18 +231,18 @@ bool physics::Vehicle::readBPT(std::string const &line) std::string braketype; int idx = 0; parser >> idx; - parser >> brakes.pressureTable[idx].PipePressureVal >> brakes.pressureTable[idx].BrakePressureVal >> brakes.pressureTable[idx].FlowSpeedVal >> braketype; + parser >> brakes.config.pressureTable[idx].PipePressureVal >> brakes.config.pressureTable[idx].BrakePressureVal >> brakes.config.pressureTable[idx].FlowSpeedVal >> braketype; if (braketype == "Pneumatic") { - brakes.pressureTable[idx].BrakeType = TBrakeSystem::Pneumatic; + brakes.config.pressureTable[idx].BrakeType = TBrakeSystem::Pneumatic; } else if (braketype == "ElectroPneumatic") { - brakes.pressureTable[idx].BrakeType = TBrakeSystem::ElectroPneumatic; + brakes.config.pressureTable[idx].BrakeType = TBrakeSystem::ElectroPneumatic; } else { - brakes.pressureTable[idx].BrakeType = TBrakeSystem::Individual; + brakes.config.pressureTable[idx].BrakeType = TBrakeSystem::Individual; } return true; @@ -587,12 +587,12 @@ void physics::Vehicle::BrakeValveDecode(std::string const &Valve) {"CV1", CV1}, {"CV1_R", CV1_R}}; auto lookup = valvetypes.find(Valve); - brakes.distributorType = lookup != valvetypes.end() ? lookup->second : Other; + brakes.config.distributorType = lookup != valvetypes.end() ? lookup->second : Other; - if (brakes.distributorType == Other && contains(Valve, "ESt")) + if (brakes.config.distributorType == Other && contains(Valve, "ESt")) { - brakes.distributorType = ESt3; + brakes.config.distributorType = ESt3; } } @@ -602,33 +602,33 @@ void physics::Vehicle::BrakeValveDecode(std::string const &Valve) void physics::Vehicle::BrakeSubsystemDecode() { using enum TBrakeSubSystem; - brakes.subsystem = ss_None; - switch (brakes.distributorType) + brakes.config.subsystem = ss_None; + switch (brakes.config.distributorType) { using enum TBrakeValve; case W: case W_Lu_L: case W_Lu_VI: case W_Lu_XR: - brakes.subsystem = ss_W; + brakes.config.subsystem = ss_W; break; case ESt3: case ESt3AL2: case ESt4: case EP2: case EP1: - brakes.subsystem = ss_ESt; + brakes.config.subsystem = ss_ESt; break; case KE: - brakes.subsystem = ss_KE; + brakes.config.subsystem = ss_KE; break; case CV1: case CV1_L_TR: - brakes.subsystem = ss_Dako; + brakes.config.subsystem = ss_Dako; break; case LSt: case EStED: - brakes.subsystem = ss_LSt; + brakes.config.subsystem = ss_LSt; break; default: break; diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index d86a04e80..f4a3e934e 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -209,50 +209,50 @@ void physics::Vehicle::LoadFIZ_Wheels(std::string const &line) void physics::Vehicle::LoadFIZ_Brake(std::string const &line) { - extract_value(brakes.distributorParameters, "BrakeValve", line, ""); - BrakeValveDecode(brakes.distributorParameters); + extract_value(brakes.config.distributorParameters, "BrakeValve", line, ""); + BrakeValveDecode(brakes.config.distributorParameters); BrakeSubsystemDecode(); - extract_value(brakes.blocksPerAxle, "NBpA", line, ""); - extract_value(brakes.maxForce, "MBF", line, ""); - extract_value(brakes.distributorSize, "Size", line, ""); - extract_value(brakes.trackBrakeForce, "TBF", line, ""); - brakes.trackBrakeForce *= 1000.0; + extract_value(brakes.config.blocksPerAxle, "NBpA", line, ""); + extract_value(brakes.config.maxForce, "MBF", line, ""); + extract_value(brakes.config.distributorSize, "Size", line, ""); + extract_value(brakes.config.trackBrakeForce, "TBF", line, ""); + brakes.config.trackBrakeForce *= 1000.0; - extract_value(brakes.maxCylinderPressure[3], "MaxBP", line, ""); - if (brakes.maxCylinderPressure[3] > 0.0) + extract_value(brakes.config.maxCylinderPressure[3], "MaxBP", line, ""); + if (brakes.config.maxCylinderPressure[3] > 0.0) { - extract_value(brakes.cylinders.count, "BCN", line, ""); - if (brakes.cylinders.count > 0) + extract_value(brakes.config.cylinders.count, "BCN", line, ""); + if (brakes.config.cylinders.count > 0) { - extract_value(brakes.maxCylinderPressure[0], "MaxLBP", line, ""); - if (brakes.maxCylinderPressure[0] < 0.01) + extract_value(brakes.config.maxCylinderPressure[0], "MaxLBP", line, ""); + if (brakes.config.maxCylinderPressure[0] < 0.01) { - brakes.maxCylinderPressure[0] = brakes.maxCylinderPressure[3]; + brakes.config.maxCylinderPressure[0] = brakes.config.maxCylinderPressure[3]; } - extract_value(brakes.maxCylinderPressure[1], "TareMaxBP", line, ""); - extract_value(brakes.maxCylinderPressure[2], "MedMaxBP", line, ""); - extract_value(brakes.maxCylinderPressure[4], "MaxASBP", line, ""); - if (brakes.maxCylinderPressure[4] < 0.01) + extract_value(brakes.config.maxCylinderPressure[1], "TareMaxBP", line, ""); + extract_value(brakes.config.maxCylinderPressure[2], "MedMaxBP", line, ""); + extract_value(brakes.config.maxCylinderPressure[4], "MaxASBP", line, ""); + if (brakes.config.maxCylinderPressure[4] < 0.01) { - brakes.maxCylinderPressure[4] = 0.0; + brakes.config.maxCylinderPressure[4] = 0.0; } - extract_value(brakes.cylinders.radius, "BCR", line, ""); - extract_value(brakes.cylinders.stroke, "BCD", line, ""); - extract_value(brakes.cylinders.springForce, "BCS", line, ""); - extract_value(brakes.cylinders.slackAdjusterForce, "BSA", line, ""); - extract_value(brakes.cylinders.riggingEfficiency, "BRE", line, "1"); + extract_value(brakes.config.cylinders.radius, "BCR", line, ""); + extract_value(brakes.config.cylinders.stroke, "BCD", line, ""); + extract_value(brakes.config.cylinders.springForce, "BCS", line, ""); + extract_value(brakes.config.cylinders.slackAdjusterForce, "BSA", line, ""); + extract_value(brakes.config.cylinders.riggingEfficiency, "BRE", line, "1"); - extract_value(brakes.cylinders.leverRatio[0], "BCM", line, ""); - extract_value(brakes.cylinders.leverRatio[1], "BCMlo", line, ""); - extract_value(brakes.cylinders.leverRatio[2], "BCMHi", line, ""); + extract_value(brakes.config.cylinders.leverRatio[0], "BCM", line, ""); + extract_value(brakes.config.cylinders.leverRatio[1], "BCMlo", line, ""); + extract_value(brakes.config.cylinders.leverRatio[2], "BCMHi", line, ""); - brakes.pressureToForce = 100 * M_PI * std::pow(brakes.cylinders.radius, 2); // w kN/bar + brakes.config.pressureToForce = 100 * M_PI * std::pow(brakes.config.cylinders.radius, 2); // w kN/bar - if (brakes.cylinders.leverRatio[1] > 0.0 || brakes.maxCylinderPressure[1] > 0.0) + if (brakes.config.cylinders.leverRatio[1] > 0.0 || brakes.config.maxCylinderPressure[1] > 0.0) { brakes.loadSetting = 1; } @@ -261,24 +261,24 @@ void physics::Vehicle::LoadFIZ_Brake(std::string const &line) brakes.loadSetting = 0; } - brakes.cylinderVolume = M_PI * std::pow(brakes.cylinders.radius, 2) * brakes.cylinders.stroke * brakes.cylinders.count; - extract_value(brakes.valveVolume, "BVV", line, ""); + brakes.config.cylinderVolume = M_PI * std::pow(brakes.config.cylinders.radius, 2) * brakes.config.cylinders.stroke * brakes.config.cylinders.count; + extract_value(brakes.config.valveVolume, "BVV", line, ""); { std::map> brakemethods{{"P10-Bg", bp_P10Bg}, {"P10-Bgu", bp_P10Bgu}, {"FR513", bp_FR513}, {"FR510", bp_FR510}, {"Cosid", bp_Cosid}, {"P10yBg", bp_P10yBg}, {"P10yBgu", bp_P10yBgu}, {"Disk1", bp_D1}, {"Disk1+Mg", bp_D1 + bp_MHS}, {"Disk2", bp_D2}}; auto lookup = brakemethods.find(extract_value("BM", line)); - brakes.method = lookup != brakemethods.end() ? lookup->second : 0; + brakes.config.method = lookup != brakemethods.end() ? lookup->second : 0; } - extract_value(brakes.rapidRatio, "RM", line, "1"); - extract_value(brakes.rapidSpeed, "RV", line, "55"); + extract_value(brakes.config.rapidRatio, "RM", line, "1"); + extract_value(brakes.config.rapidSpeed, "RV", line, "55"); } } else { // maxbrakepress[3] == 0 or less - brakes.pressureToForce = 0; + brakes.config.pressureToForce = 0; } // Ra 2014-07: trochę niedokładności @@ -286,10 +286,10 @@ void physics::Vehicle::LoadFIZ_Brake(std::string const &line) auto const firstdraw{Random(10)}; brakes.controlReservoirPressure = 5 + 0.001 * (Random(10) - firstdraw); extract_value(brakes.controlReservoirPressure, "HiPP", line, ""); - brakes.pipeHighPressure = brakes.controlReservoirPressure; - brakes.pipeLowPressure = std::min(brakes.pipeHighPressure, 3.5); - extract_value(brakes.pipeLowPressure, "LoPP", line, ""); - brakes.pipePressureRange = brakes.pipeHighPressure - brakes.pipeLowPressure; + brakes.config.pipeHighPressure = brakes.controlReservoirPressure; + brakes.config.pipeLowPressure = std::min(brakes.config.pipeHighPressure, 3.5); + extract_value(brakes.config.pipeLowPressure, "LoPP", line, ""); + brakes.config.pipePressureRange = brakes.config.pipeHighPressure - brakes.config.pipeLowPressure; extract_value(air.config.mainReservoirVolume, "Vv", line, ""); /* @@ -304,13 +304,13 @@ void physics::Vehicle::LoadFIZ_Brake(std::string const &line) extract_value(brakes.emergencyValve.offPressure, "MinEVP", line, ""); extract_value(brakes.emergencyValve.onPressure, "MaxEVP", line, ""); extract_value(brakes.emergencyValve.area, "EVArea", line, ""); - extract_value(brakes.universalButtonActions[0], "UBB1", line, ""); - extract_value(brakes.universalButtonActions[1], "UBB2", line, ""); - extract_value(brakes.universalButtonActions[2], "UBB3", line, ""); + extract_value(brakes.config.universalButtonActions[0], "UBB1", line, ""); + extract_value(brakes.config.universalButtonActions[1], "UBB2", line, ""); + extract_value(brakes.config.universalButtonActions[2], "UBB3", line, ""); extract_value(brakes.pipeLock.onPressure, "LPOn", line, "-1"); extract_value(brakes.pipeLock.offPressure, "LPOff", line, "-1"); extract_value(brakes.pipeLock.unlockHandlePosition, "HandlePipeUnlockPos", line, "-3"); - extract_value(brakes.emergencyCutsOffDriverValve, "EmergencyCutsOffHandle", line, ""); + extract_value(brakes.config.emergencyCutsOffDriverValve, "EmergencyCutsOffHandle", line, ""); { using enum CompressorSupply; std::map> compressorpowers{ @@ -691,9 +691,9 @@ void physics::Vehicle::LoadFIZ_CntrlBrakes(std::string const &line) using enum TBrakeSystem; std::map> brakesystems{{"Pneumatic", Pneumatic}, {"ElectroPneumatic", ElectroPneumatic}}; auto lookup = brakesystems.find(extract_value("BrakeSystem", line)); - brakes.kind = lookup != brakesystems.end() ? lookup->second : Individual; + brakes.config.kind = lookup != brakesystems.end() ? lookup->second : Individual; } - if (brakes.kind != TBrakeSystem::Individual) + if (brakes.config.kind != TBrakeSystem::Individual) { LoadFIZ_CntrlTrainBrake(line); } // brakesystem != individual @@ -703,10 +703,10 @@ void physics::Vehicle::LoadFIZ_CntrlBrakes(std::string const &line) using enum TLocalBrake; std::map> localbrakes{{"ManualBrake", ManualBrake}, {"PneumaticBrake", PneumaticBrake}, {"HydraulicBrake", HydraulicBrake}}; auto lookup = localbrakes.find(extract_value("LocalBrake", line)); - brakes.localKind = lookup != localbrakes.end() ? lookup->second : NoBrake; + brakes.config.localKind = lookup != localbrakes.end() ? lookup->second : NoBrake; } // mbrake - extract_value(brakes.hasHandBrake, "ManualBrake", line, ""); + extract_value(brakes.config.hasHandBrake, "ManualBrake", line, ""); } // Cntrl.: of a vehicle with a train brake, its positions, delays, modes, handles, load weighing and anti-slip brake @@ -714,11 +714,11 @@ void physics::Vehicle::LoadFIZ_CntrlTrainBrake(std::string const &line) { using enum TBrakeHandle; - extract_value(brakes.handlePositions, "BCPN", line, ""); + extract_value(brakes.config.handlePositions, "BCPN", line, ""); for (int idx = 0; idx < 4; ++idx) { - extract_value(brakes.delays[idx], std::format("BDelay{}", idx + 1), line, ""); + extract_value(brakes.config.delays[idx], std::format("BDelay{}", idx + 1), line, ""); } // brakedelays, brakedelayflag { @@ -734,7 +734,7 @@ void physics::Vehicle::LoadFIZ_CntrlTrainBrake(std::string const &line) std::string brakedelay; extract_value(brakedelay, "BrakeDelays", line, ""); auto lookup = brakedelays.find(brakedelay); - brakes.availableDelays = lookup != brakedelays.end() ? lookup->second : 0; + brakes.config.availableDelays = lookup != brakedelays.end() ? lookup->second : 0; lookup = brakedelayflags.find(brakedelay); brakes.delaySetting = lookup != brakedelayflags.end() ? lookup->second : 0; } @@ -742,7 +742,7 @@ void physics::Vehicle::LoadFIZ_CntrlTrainBrake(std::string const &line) { 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)); - brakes.availableOperatingModes = lookup != brakeopmodes.end() ? lookup->second : 0; + brakes.config.availableOperatingModes = lookup != brakeopmodes.end() ? lookup->second : 0; } // brakehandle { @@ -751,26 +751,26 @@ void physics::Vehicle::LoadFIZ_CntrlTrainBrake(std::string const &line) {"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)); - brakes.driverValveType = lookup != brakehandles.end() ? lookup->second : NoHandle; + brakes.config.driverValveType = lookup != brakehandles.end() ? lookup->second : NoHandle; } - extract_value(brakes.driverValveSettings.automaticOverload, "HAO", line, ""); - extract_value(brakes.driverValveSettings.manualOverload, "HMO", line, ""); - extract_value(brakes.driverValveSettings.genericParameter1, "HGDP1", line, ""); - extract_value(brakes.driverValveSettings.genericParameter2, "HGDP2", line, ""); - extract_value(brakes.driverValveSettings.overloadMaxPressure, "OMP", line, ""); - extract_value(brakes.driverValveSettings.overloadPressureDecrease, "OPD", line, ""); + extract_value(brakes.config.driverValveSettings.automaticOverload, "HAO", line, ""); + extract_value(brakes.config.driverValveSettings.manualOverload, "HMO", line, ""); + extract_value(brakes.config.driverValveSettings.genericParameter1, "HGDP1", line, ""); + extract_value(brakes.config.driverValveSettings.genericParameter2, "HGDP2", line, ""); + extract_value(brakes.config.driverValveSettings.overloadMaxPressure, "OMP", line, ""); + extract_value(brakes.config.driverValveSettings.overloadPressureDecrease, "OPD", line, ""); // brakelochandle { std::map> locbrakehandles{{"FD1", FD1}, {"Knorr", Knorr}, {"Westinghouse", West}}; auto lookup = locbrakehandles.find(extract_value("LocBrakeHandle", line)); - brakes.independentValveType = lookup != locbrakehandles.end() ? lookup->second : NoHandle; + brakes.config.independentValveType = lookup != locbrakehandles.end() ? lookup->second : NoHandle; } // mbpm - if (true == extract_value(brakes.maxPressureMass, "MaxBPMass", line, "")) + if (true == extract_value(brakes.config.maxPressureMass, "MaxBPMass", line, "")) { // NOTE: only convert the value from tons to kilograms if the entry is present in the config file - brakes.maxPressureMass *= 1000.0; + brakes.config.maxPressureMass *= 1000.0; } // asbtype @@ -782,15 +782,15 @@ void physics::Vehicle::LoadFIZ_CntrlAntiSlipBrake(std::string_view const asb) { if (asb == "yes") { - brakes.antiSlipType = 128; + brakes.config.antiSlipType = 128; } - else if (brakes.handlePositions > 0 && asb == "manual") + else if (brakes.config.handlePositions > 0 && asb == "manual") { - brakes.antiSlipType = 1; + brakes.config.antiSlipType = 1; } - else if (brakes.handlePositions > 0 && asb == "automatic") + else if (brakes.config.handlePositions > 0 && asb == "automatic") { - brakes.antiSlipType = 2; + brakes.config.antiSlipType = 2; } } @@ -855,7 +855,7 @@ void physics::Vehicle::LoadFIZ_CntrlControllers(std::string const &line) extract_value(HasCamshaft, "Camshaft", line, ""); extract_value(EIMCtrlType, "EIMCtrlType", line, ""); EIMCtrlType = std::clamp(EIMCtrlType, 0, 3); - extract_value(brakes.independentTraxx, "LocalBrakeTraxx", line, ""); + extract_value(brakes.config.independentTraxx, "LocalBrakeTraxx", line, ""); extract_value(EIMCtrlAdditionalZeros, "EIMCtrlAddZeros", line, ""); extract_value(EIMCtrlEmergency, "EIMCtrlEmergency", line, ""); // Elf (EIMCtrlType 2): an emergency brake position below the controller's position 0, which shifts the other positions up by one diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 3fc4ba6a0..7abac3c67 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -46,13 +46,13 @@ void physics::Vehicle::BrakeLevelSet(double b) brakes.handlePositionReal = brakes.handlePositionSmooth; auto x = static_cast(std::floor(brakes.handlePositionSmooth)); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być // obcięte a nie zaokrągone - while (x > brakes.handlePosition && brakes.handlePosition < brakes.handlePositions) // jeśli zwiększyło się o 1 + while (x > brakes.handlePosition && brakes.handlePosition < brakes.config.handlePositions) // jeśli zwiększyło się o 1 if (!IncBrakeLevelOld()) // physics::Vehicle:: break; // wyjście awaryjne while (x < brakes.handlePosition && brakes.handlePosition >= -1) // jeśli zmniejszyło się o 1 if (!DecBrakeLevelOld()) // physics::Vehicle:: break; - brakes.actualPressure = brakes.pressureTable[brakes.handlePosition]; // skopiowanie pozycji + brakes.actualPressure = brakes.config.pressureTable[brakes.handlePosition]; // skopiowanie pozycji /* //youBy: obawiam sie, ze tutaj to nie dziala :P //Ra 2014-03: było tak zrobione, że działało - po każdej zmianie pozycji była wywoływana ta @@ -77,7 +77,7 @@ bool physics::Vehicle::BrakeLevelAdd(double b) { // dodanie wartości (b) do pozycji hamulca (w tym ujemnej) // zwraca false, gdy po dodaniu było by poza zakresem BrakeLevelSet(brakes.handlePositionSmooth + b); - return b > 0.0 ? brakes.handlePositionSmooth < brakes.handlePositions : brakes.handlePosition > -1.0; // true, jeśli można kontynuować + return b > 0.0 ? brakes.handlePositionSmooth < brakes.config.handlePositions : brakes.handlePosition > -1.0; // true, jeśli można kontynuować }; bool physics::Vehicle::IncBrakeLevel() @@ -136,7 +136,7 @@ ZN //masa double physics::Vehicle::LocalBrakeRatio(void) const { double LBR; - if (brakes.driverValveType == TBrakeHandle::MHZ_EN57) + if (brakes.config.driverValveType == TBrakeHandle::MHZ_EN57) if (brakes.operatingMode >= bom_EP) LBR = brakes.driverValve->GetEP(brakes.handlePositionReal); else @@ -174,8 +174,8 @@ double physics::Vehicle::ManualBrakeRatio(void) const // ***************************************************************************** double physics::Vehicle::BrakeVP(void) const { - if (brakes.valveVolume > 0) - return brakes.reservoirAir / (10.0 * brakes.valveVolume); + if (brakes.config.valveVolume > 0) + return brakes.reservoirAir / (10.0 * brakes.config.valveVolume); else return 0; } @@ -188,8 +188,8 @@ double physics::Vehicle::RealPipeRatio(void) const { double rpp; - if (brakes.pipePressureRange > 0) - rpp = (brakes.controlReservoirPressure - brakePipe.Pressure()) / brakes.pipePressureRange; + if (brakes.config.pipePressureRange > 0) + rpp = (brakes.controlReservoirPressure - brakePipe.Pressure()) / brakes.config.pipePressureRange; else rpp = 0; return rpp; @@ -203,13 +203,13 @@ double physics::Vehicle::PipeRatio(void) const { double pr; - if (brakes.pipePressureRange > 0) + if (brakes.config.pipePressureRange > 0) if (false) // SPKS!! no to jak nie wchodzimy to po co branch? { - if (3.0 * brakePipe.Pressure() > brakes.pipeHighPressure + brakes.pipeLowPressure + brakes.pipeLowPressure) - pr = (brakes.pipeHighPressure - std::min(brakes.pipeHighPressure, brakePipe.Pressure())) / (brakes.pipePressureRange * 4.0 / 3.0); + if (3.0 * brakePipe.Pressure() > brakes.config.pipeHighPressure + brakes.config.pipeLowPressure + brakes.config.pipeLowPressure) + pr = (brakes.config.pipeHighPressure - std::min(brakes.config.pipeHighPressure, brakePipe.Pressure())) / (brakes.config.pipePressureRange * 4.0 / 3.0); else - pr = (brakes.pipeHighPressure - 1.0 / 3.0 * brakes.pipePressureRange - std::max(brakes.pipeLowPressure, brakePipe.Pressure())) / (brakes.pipePressureRange * 2.0 / 3.0); + pr = (brakes.config.pipeHighPressure - 1.0 / 3.0 * brakes.config.pipePressureRange - std::max(brakes.config.pipeLowPressure, brakePipe.Pressure())) / (brakes.config.pipePressureRange * 2.0 / 3.0); // if (not TestFlag(BrakeStatus, b_Ractive)) // and(BrakeMethod and 1 = 0) and TestFlag(BrakeDelays, bdelay_R) and (Power < 1) and // (BrakeCtrlPos < 1) then pr : = std::min(0.5, pr); @@ -217,7 +217,7 @@ double physics::Vehicle::PipeRatio(void) const // then pr : = pr * 1.333; // dziwny rapid wywalamy } else - pr = (brakes.pipeHighPressure - std::max(brakes.pipeLowPressure, std::min(brakes.pipeHighPressure, brakePipe.Pressure()))) / brakes.pipePressureRange; + pr = (brakes.config.pipeHighPressure - std::max(brakes.config.pipeLowPressure, std::min(brakes.config.pipeHighPressure, brakePipe.Pressure()))) / brakes.config.pipePressureRange; else pr = 0; return pr; @@ -352,14 +352,14 @@ bool physics::Vehicle::IncBrakeLevelOld(void) { bool IBLO = false; - if (brakes.handlePositions > 0) + if (brakes.config.handlePositions > 0) { - if (brakes.handlePosition < brakes.handlePositions) + if (brakes.handlePosition < brakes.config.handlePositions) { ++brakes.handlePosition; // youBy: EP po nowemu IBLO = true; - if (brakes.actualPressure.PipePressureVal < 0 && brakes.pressureTable[brakes.handlePosition - 1].PipePressureVal > 0) + if (brakes.actualPressure.PipePressureVal < 0 && brakes.config.pressureTable[brakes.handlePosition - 1].PipePressureVal > 0) brakes.pipeLimiterPressure = brakePipe.Pressure(); } else @@ -379,9 +379,9 @@ bool physics::Vehicle::DecBrakeLevelOld(void) { bool DBLO = false; - if (brakes.handlePositions > 0) + if (brakes.config.handlePositions > 0) { - if (brakes.handlePosition > (brakes.driverValveType == TBrakeHandle::FV4a ? -2 : -1)) + if (brakes.handlePosition > (brakes.config.driverValveType == TBrakeHandle::FV4a ? -2 : -1)) { --brakes.handlePosition; // youBy: EP po nowemu @@ -499,7 +499,7 @@ bool physics::Vehicle::AlarmChainSwitch(bool const State) bool physics::Vehicle::AntiSlippingBrake(void) { bool ASB = false; // Ra: przeniesione z końca - if (brakes.antiSlipType == 1) + if (brakes.config.antiSlipType == 1) { ASB = true; // SPKS!! brakes.distributor->ASB(1); @@ -545,7 +545,7 @@ bool physics::Vehicle::UniversalBrakeButton(int button, int state) { for (int i = 0; i < 3; i++) { - flag = flag | (brakes.universalButtonPressed[i] ? brakes.universalButtonActions[i] : 0); + flag = flag | (brakes.universalButtonPressed[i] ? brakes.config.universalButtonActions[i] : 0); } } @@ -555,7 +555,7 @@ bool physics::Vehicle::UniversalBrakeButton(int button, int state) brakes.pipeLock.unlockPressed = (flag & TUniversalBrake::ub_UnlockPipe) > 0; // if the releaser can be activated by switch - if (TestFlag(brakes.universalButtonActions[0] & brakes.universalButtonActions[1] & brakes.universalButtonActions[2], TUniversalBrake::ub_Release)) + if (TestFlag(brakes.config.universalButtonActions[0] & brakes.config.universalButtonActions[1] & brakes.config.universalButtonActions[2], TUniversalBrake::ub_Release)) { BrakeReleaser(TestFlag(flag, TUniversalBrake::ub_Release) ? 1 : 0); } @@ -571,7 +571,7 @@ bool physics::Vehicle::SwitchEPBrake(int state) bool OK; OK = false; - if (brakes.driverValveType == TBrakeHandle::St113 && CabOccupied != 0) + if (brakes.config.driverValveType == TBrakeHandle::St113 && CabOccupied != 0) { // the handle works the EP contactors pneumatically, their supply is cut as the Oerlikon handle's is if (state > 0 && EPBrakeControlPowered()) @@ -676,15 +676,15 @@ bool physics::Vehicle::IncBrakeMult(void) { bool IBM; - if (brakes.loadSetting > 0 && brakes.maxPressureMass < 2 && brakes.loadSetting < 3) + if (brakes.loadSetting > 0 && brakes.config.maxPressureMass < 2 && brakes.loadSetting < 3) { - if (brakes.maxCylinderPressure[2] > 0 && brakes.loadSetting == 1) + if (brakes.config.maxCylinderPressure[2] > 0 && brakes.loadSetting == 1) brakes.loadSetting = 2; else brakes.loadSetting = 3; IBM = true; - if (brakes.cylinders.leverRatio[2] > 0) - brakes.cylinders.leverRatio[0] = brakes.cylinders.leverRatio[2]; + if (brakes.config.cylinders.leverRatio[2] > 0) + brakes.config.cylinders.leverRatio[0] = brakes.config.cylinders.leverRatio[2]; } else IBM = false; @@ -699,15 +699,15 @@ bool physics::Vehicle::IncBrakeMult(void) bool physics::Vehicle::DecBrakeMult(void) { bool DBM; - if (brakes.loadSetting > 1 && brakes.maxPressureMass < 2) + if (brakes.loadSetting > 1 && brakes.config.maxPressureMass < 2) { - if (brakes.maxCylinderPressure[2] > 0 && brakes.loadSetting == 3) + if (brakes.config.maxCylinderPressure[2] > 0 && brakes.loadSetting == 3) brakes.loadSetting = 2; else brakes.loadSetting = 1; DBM = true; - if (brakes.cylinders.leverRatio[1] > 0) - brakes.cylinders.leverRatio[0] = brakes.cylinders.leverRatio[1]; + if (brakes.config.cylinders.leverRatio[1] > 0) + brakes.config.cylinders.leverRatio[0] = brakes.config.cylinders.leverRatio[1]; } else DBM = false; @@ -816,7 +816,7 @@ void physics::Vehicle::UpdatePipePressure(double dt) brakes.driverValveFlow = 0; - if (brakes.handlePositions > 1) + if (brakes.config.handlePositions > 1) { UpdateLocalBrakeValve(dt); @@ -832,7 +832,7 @@ void physics::Vehicle::UpdatePipePressure(double dt) // Pipe.Flow(PF(PipePress, 0, d2A(7)) * dt); // if ConverterFlag then // Pipe.Flow(PF(PipePress, 0, d2A(12)) * dt); - brakes.driverValveFlow = brakes.driverValveFlow / (Dim.L * brakes.pipeSection * 20); + brakes.driverValveFlow = brakes.driverValveFlow / (Dim.L * brakes.config.pipeSection * 20); brakes.controlReservoirPressure = brakes.distributor->GetVRP(); // ciśnienie komory wstępnej rozdzielacza @@ -840,11 +840,11 @@ void physics::Vehicle::UpdatePipePressure(double dt) UpdateDistributorSettings(); - if ((brakes.driverValveType == TBrakeHandle::FVel6 || brakes.driverValveType == TBrakeHandle::FVE408) && CabOccupied != 0) + if ((brakes.config.driverValveType == TBrakeHandle::FVel6 || brakes.config.driverValveType == TBrakeHandle::FVE408) && CabOccupied != 0) { UpdateEPBrake(); } - else if (brakes.driverValveType == TBrakeHandle::St113 && CabOccupied != 0 && std::abs(EpForce) > 0.001 && !EPBrakeControlPowered()) + else if (brakes.config.driverValveType == 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); @@ -860,7 +860,7 @@ void physics::Vehicle::UpdatePipePressure(double dt) // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() brakePipe.SetCouplersPending(true); - if (brakes.antiSlipType == 128) + if (brakes.config.antiSlipType == 128) brakes.distributor->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); brakes.pipeFlow = 0; @@ -887,7 +887,7 @@ void physics::Vehicle::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 = brakes.independentTraxx ? eim_localbrake : brakes.independentPosition; + double lbpa = brakes.config.independentTraxx ? eim_localbrake : brakes.independentPosition; if (EIMCtrlType > 0 && UniCtrlIntegratedLocalBrakeCtrl) { lbpa = std::max(0.0, -eimic_real); @@ -905,7 +905,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) // 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 (brakes.independentTraxx) + if (brakes.config.independentTraxx) { lbpa = eim_localbrake; } @@ -932,10 +932,10 @@ void physics::Vehicle::UpdateMainValve(double dt) // the driver's valve of a vehicle prepared for hauling is cut out, whatever its handle shows brakes.driverValveFlow = 0; } - else if ((brakes.availableOperatingModes & bom_PS) == 0 || (CabOccupied != 0 && brakes.operatingMode != bom_PS)) + else if ((brakes.config.availableOperatingModes & bom_PS) == 0 || (CabOccupied != 0 && brakes.operatingMode != bom_PS)) { - if (brakes.operatingMode < bom_EP || brakes.driverValve->GetPos(bh_EB) - 0.5 < brakes.handlePositionReal || (brakes.driverValveType != TBrakeHandle::MHZ_EN57 && brakes.driverValveType != TBrakeHandle::MHZ_K8P)) + if (brakes.operatingMode < bom_EP || brakes.driverValve->GetPos(bh_EB) - 0.5 < brakes.handlePositionReal || (brakes.config.driverValveType != TBrakeHandle::MHZ_EN57 && brakes.config.driverValveType != TBrakeHandle::MHZ_K8P)) { brakes.driverValveFlow = brakes.driverValve->GetPF(MainValveHandlePosition(), brakePipe.Pressure(), temp, dt, brakes.equivalentPipePressure); } @@ -965,9 +965,9 @@ void physics::Vehicle::UpdateMainValve(double dt) double physics::Vehicle::MainValveSupply() { brakes.pipeLock.locked = brakePipe.Pressure() < (brakes.pipeLock.locked ? brakes.pipeLock.offPressure : brakes.pipeLock.onPressure); - bool lock_new = (brakes.pipeLock.locked && !brakes.pipeLock.unlockPressed && brakes.handlePositionReal > brakes.pipeLock.unlockHandlePosition) || (brakes.emergencyCutsOffDriverValve && brakes.emergencyValve.flow > 0); // new simple codition based on .fiz - bool lock_old = brakes.driverValveType == TBrakeHandle::FV4a // old complex condition based on assumptions - && brakePipe.Pressure() < 2.75 && (brakes.distributor->GetStatus() & b_rls) == 0 && brakes.subsystem == TBrakeSubSystem::ss_LSt && TrainType != train_type::emu && !brakes.pipeLock.unlockPressed; + bool lock_new = (brakes.pipeLock.locked && !brakes.pipeLock.unlockPressed && brakes.handlePositionReal > brakes.pipeLock.unlockHandlePosition) || (brakes.config.emergencyCutsOffDriverValve && brakes.emergencyValve.flow > 0); // new simple codition based on .fiz + bool lock_old = brakes.config.driverValveType == TBrakeHandle::FV4a // old complex condition based on assumptions + && brakePipe.Pressure() < 2.75 && (brakes.distributor->GetStatus() & b_rls) == 0 && brakes.config.subsystem == TBrakeSubSystem::ss_LSt && TrainType != train_type::emu && !brakes.pipeLock.unlockPressed; if (lock_old || lock_new) { @@ -1015,23 +1015,23 @@ void physics::Vehicle::UpdateEmergencyValve(double dt) // what the distributor valve gets of the local brake and the load, by its kind void physics::Vehicle::UpdateDistributorSettings() { - switch (brakes.distributorType) + switch (brakes.config.distributorType) { case TBrakeValve::K: case TBrakeValve::W: { - if (brakes.independentValveType != TBrakeHandle::NoHandle) + if (brakes.config.independentValveType != TBrakeHandle::NoHandle) { brakes.independentCylinderPressure = brakes.independentValve->GetCP(); //(Hamulec as TWest).SetLBP(LocBrakePress); brakes.distributor->SetLBP(brakes.independentCylinderPressure); } - if (brakes.maxPressureMass < 2) + if (brakes.config.maxPressureMass < 2) //(Hamulec as TWest).PLC(MaxBrakePress[LoadFlag]) - brakes.distributor->PLC(brakes.maxCylinderPressure[brakes.loadSetting]); + brakes.distributor->PLC(brakes.config.maxCylinderPressure[brakes.loadSetting]); else //(Hamulec as TWest).PLC(TotalMass); brakes.distributor->PLC(TotalMass - Mred); @@ -1060,10 +1060,10 @@ void physics::Vehicle::UpdateDistributorSettings() //(Hamulec as TLSt).SetLBP(LocBrakePress); brakes.distributor->SetLBP(brakes.independentCylinderPressure); - if (brakes.distributorType == TBrakeValve::EStED) + if (brakes.config.distributorType == TBrakeValve::EStED) { - if (brakes.maxPressureMass < 2) - brakes.distributor->PLC(brakes.maxCylinderPressure[brakes.loadSetting]); + if (brakes.config.maxPressureMass < 2) + brakes.distributor->PLC(brakes.config.maxCylinderPressure[brakes.loadSetting]); else brakes.distributor->PLC(TotalMass - Mred); } @@ -1089,9 +1089,9 @@ void physics::Vehicle::UpdateDistributorSettings() case TBrakeValve::ESt4: case TBrakeValve::ESt3: { - if (brakes.maxPressureMass < 2) + if (brakes.config.maxPressureMass < 2) //(Hamulec as TNESt3).PLC(MaxBrakePress[LoadFlag]) - brakes.distributor->PLC(brakes.maxCylinderPressure[brakes.loadSetting]); + brakes.distributor->PLC(brakes.config.maxCylinderPressure[brakes.loadSetting]); else //(Hamulec as TNESt3).PLC(TotalMass); brakes.distributor->PLC(TotalMass - Mred); @@ -1105,9 +1105,9 @@ void physics::Vehicle::UpdateDistributorSettings() brakes.independentCylinderPressure = brakes.independentValve->GetCP(); //(Hamulec as TKE).SetLBP(LocBrakePress); brakes.distributor->SetLBP(brakes.independentCylinderPressure); - if (brakes.maxPressureMass < 2) + if (brakes.config.maxPressureMass < 2) //(Hamulec as TKE).PLC(MaxBrakePress[LoadFlag]) - brakes.distributor->PLC(brakes.maxCylinderPressure[brakes.loadSetting]); + brakes.distributor->PLC(brakes.config.maxCylinderPressure[brakes.loadSetting]); else //(Hamulec as TKE).PLC(TotalMass); brakes.distributor->PLC(TotalMass - Mred); @@ -1258,7 +1258,7 @@ double physics::Vehicle::GetDVc(double dt) if (Couplers[0].Connected != nullptr && Couplers[0].CouplingFlag.HasAll(Coupling::brakeHose)) { //*0.85 c = Couplers[0].Connected; // skrot //0.08 //e/D * L/D = e/D^2 * L - dv1 = 0.5 * dt * PF(brakePipe.Pressure(), neighbour_pipe_pressure(*c, c->brakePipe.Pressure(), *c->brakePipe.reservoir), brakes.pipeSection / (1.0 + 0.015 / brakes.pipeSection * Dim.L)); + dv1 = 0.5 * dt * PF(brakePipe.Pressure(), neighbour_pipe_pressure(*c, c->brakePipe.Pressure(), *c->brakePipe.reservoir), brakes.config.pipeSection / (1.0 + 0.015 / brakes.config.pipeSection * Dim.L)); c->brakePipe.reservoir->Flow(-dv1); if (pipe_wakes(dv1, brakePipe.Pressure(), *c->brakePipe.reservoir)) c->switch_physics(true, wake_cause::mainpipe); @@ -1267,7 +1267,7 @@ double physics::Vehicle::GetDVc(double dt) if (Couplers[1].Connected != nullptr && Couplers[1].CouplingFlag.HasAll(Coupling::brakeHose)) { c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(brakePipe.Pressure(), neighbour_pipe_pressure(*c, c->brakePipe.Pressure(), *c->brakePipe.reservoir), brakes.pipeSection / (1.0 + 0.015 / brakes.pipeSection * Dim.L)); + dv2 = 0.5 * dt * PF(brakePipe.Pressure(), neighbour_pipe_pressure(*c, c->brakePipe.Pressure(), *c->brakePipe.reservoir), brakes.config.pipeSection / (1.0 + 0.015 / brakes.config.pipeSection * Dim.L)); c->brakePipe.reservoir->Flow(-dv2); if (pipe_wakes(dv2, brakePipe.Pressure(), *c->brakePipe.reservoir)) c->switch_physics(true, wake_cause::mainpipe); @@ -1340,7 +1340,7 @@ struct train_pipe train_pipe const brake_pipe{&physics::Vehicle::brakePipe, Coupling::brakeHose, &physics::Vehicle::GetDVc, - [](physics::Vehicle const &Vehicle) { return Vehicle.brakes.pipeSection / (1.0 + 0.015 / Vehicle.brakes.pipeSection * Vehicle.Dim.L); }}; + [](physics::Vehicle const &Vehicle) { return Vehicle.brakes.config.pipeSection / (1.0 + 0.015 / Vehicle.brakes.config.pipeSection * Vehicle.Dim.L); }}; // the main reservoir pipe, GetScndDVc() train_pipe const main_reservoir_pipe{&physics::Vehicle::mainPipe, Coupling::mainHose, diff --git a/physics/components/securitysystem.cpp b/physics/components/securitysystem.cpp index 3671c0b4b..d42ef208a 100644 --- a/physics/components/securitysystem.cpp +++ b/physics/components/securitysystem.cpp @@ -266,7 +266,7 @@ void physics::Vehicle::SecuritySystemCheck(double dt) bool physics::Vehicle::RadiostopSwitch(bool Switch) { bool EBS; - if (brakes.kind != TBrakeSystem::Individual && brakes.handlePositions > 0) + if (brakes.config.kind != TBrakeSystem::Individual && brakes.config.handlePositions > 0) { if (true == Switch && false == RadioStopFlag) diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index 424132c0c..aea52146f 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -71,16 +71,16 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) // WriteLogSS("aa ok", BoolToYN(OK)); } - if (brakes.kind == TBrakeSystem::Individual && brakes.subsystem != TBrakeSubSystem::ss_None) + if (brakes.config.kind == TBrakeSystem::Individual && brakes.config.subsystem != TBrakeSubSystem::ss_None) OK = false; //! - if (brakes.valveVolume == 0 && brakes.maxCylinderPressure[3] > 0 && brakes.kind != TBrakeSystem::Individual) + if (brakes.config.valveVolume == 0 && brakes.config.maxCylinderPressure[3] > 0 && brakes.config.kind != TBrakeSystem::Individual) { - brakes.valveVolume = brakes.maxCylinderPressure[3] / (5.0 - brakes.maxCylinderPressure[3]) * (brakes.cylinders.radius * brakes.cylinders.radius * brakes.cylinders.stroke * brakes.cylinders.count * M_PI) * 1000; + brakes.config.valveVolume = brakes.config.maxCylinderPressure[3] / (5.0 - brakes.config.maxCylinderPressure[3]) * (brakes.config.cylinders.radius * brakes.config.cylinders.radius * brakes.config.cylinders.stroke * brakes.config.cylinders.count * M_PI) * 1000; } - if (brakes.valveVolume == 0.0) + if (brakes.config.valveVolume == 0.0) { - brakes.valveVolume = 0.01; + brakes.config.valveVolume = 0.01; } // WriteLog("BVV = " + FloatToStr(BrakeVVolume)); @@ -130,7 +130,7 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) ActFlowSpeed = 0.0; brakes.handlePositionReal = brakes.handlePosition; - if (brakes.independentValveType == TBrakeHandle::Knorr) + if (brakes.config.independentValveType == TBrakeHandle::Knorr) brakes.independentPosition = 0.5; brakePipe.reservoir->CreatePress(brakePipe.Pressure()); @@ -165,9 +165,9 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) // taki mini automat - powinno byc ladnie dobrze :) brakes.delaySetting = bdelay_P; - if (TestFlag(brakes.availableDelays, bdelay_G) && !TestFlag(brakes.availableDelays, bdelay_R)) + if (TestFlag(brakes.config.availableDelays, bdelay_G) && !TestFlag(brakes.config.availableDelays, bdelay_R)) brakes.delaySetting = bdelay_G; - if (TestFlag(brakes.availableDelays, bdelay_R) && !TestFlag(brakes.availableDelays, bdelay_G)) + if (TestFlag(brakes.config.availableDelays, bdelay_R) && !TestFlag(brakes.config.availableDelays, bdelay_G)) brakes.delaySetting = bdelay_R; /* // disabled, as test mode is used in specific situations and not really a default @@ -182,12 +182,12 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) for (int b = 1; b < 4; b++) { - if (brakes.delays[b] == 0) - brakes.delays[b] = DefBrakeTable[b]; - brakes.delays[b] = brakes.delays[b] * (2.5 + Random(0.0, 0.2)) / 3.0; + if (brakes.config.delays[b] == 0) + brakes.config.delays[b] = DefBrakeTable[b]; + brakes.config.delays[b] = brakes.config.delays[b] * (2.5 + Random(0.0, 0.2)) / 3.0; } - brakes.distributor->Init(brakePipe.Pressure(), brakes.pipeHighPressure, brakes.pipeLowPressure, brakes.cylinderPressure, brakes.delaySetting); + brakes.distributor->Init(brakePipe.Pressure(), brakes.config.pipeHighPressure, brakes.config.pipeLowPressure, brakes.cylinderPressure, brakes.delaySetting); /* ScndPipePress = Compressor; */ @@ -220,28 +220,28 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) // the distributor valve of the vehicle's kind void physics::Vehicle::CreateBrakeValve() { - switch (brakes.distributorType) + switch (brakes.config.distributorType) { case TBrakeValve::W: case TBrakeValve::K: { WriteLog("XBT W, K"); - brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); - if (brakes.maxPressureMass < 2) // jesli przystawka wazaca - brakes.distributor->SetLP(0, brakes.maxCylinderPressure[3], 0); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + if (brakes.config.maxPressureMass < 2) // jesli przystawka wazaca + brakes.distributor->SetLP(0, brakes.config.maxCylinderPressure[3], 0); else - brakes.distributor->SetLP(Mass, brakes.maxPressureMass, brakes.maxCylinderPressure[1]); + brakes.distributor->SetLP(Mass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); break; } case TBrakeValve::KE: { WriteLog("XBT WKE"); - brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); - brakes.distributor->SetRM(brakes.rapidRatio); - if (brakes.maxPressureMass < 2) // jesli przystawka wazaca - brakes.distributor->SetLP(0, brakes.maxCylinderPressure[3], 0); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor->SetRM(brakes.config.rapidRatio); + if (brakes.config.maxPressureMass < 2) // jesli przystawka wazaca + brakes.distributor->SetLP(0, brakes.config.maxCylinderPressure[3], 0); else - brakes.distributor->SetLP(Mass, brakes.maxPressureMass, brakes.maxCylinderPressure[1]); + brakes.distributor->SetLP(Mass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); break; } case TBrakeValve::NESt3: @@ -250,76 +250,76 @@ void physics::Vehicle::CreateBrakeValve() case TBrakeValve::ESt4: { WriteLog("XBT NESt3, ESt3, ESt3AL2, ESt4"); - brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); - static_cast(brakes.distributor.get())->SetSize(brakes.distributorSize, brakes.distributorParameters); - if (brakes.maxPressureMass < 2) // jesli przystawka wazaca - brakes.distributor->SetLP(0, brakes.maxCylinderPressure[3], 0); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + static_cast(brakes.distributor.get())->SetSize(brakes.config.distributorSize, brakes.config.distributorParameters); + if (brakes.config.maxPressureMass < 2) // jesli przystawka wazaca + brakes.distributor->SetLP(0, brakes.config.maxCylinderPressure[3], 0); else - brakes.distributor->SetLP(Mass, brakes.maxPressureMass, brakes.maxCylinderPressure[1]); + brakes.distributor->SetLP(Mass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); break; } case TBrakeValve::LSt: { WriteLog("XBT LSt"); - brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); - brakes.distributor->SetRM(brakes.rapidRatio); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor->SetRM(brakes.config.rapidRatio); break; } case TBrakeValve::EStED: { WriteLog("XBT EStED"); - brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); - brakes.distributor->SetRM(brakes.rapidRatio); - if (brakes.maxPressureMass < 2) + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor->SetRM(brakes.config.rapidRatio); + if (brakes.config.maxPressureMass < 2) { // jesli przystawka wazaca - brakes.distributor->SetLP(0, brakes.maxCylinderPressure[3], 0); + brakes.distributor->SetLP(0, brakes.config.maxCylinderPressure[3], 0); } else { - brakes.distributor->SetLP(Mass, brakes.maxPressureMass, brakes.maxCylinderPressure[1]); + brakes.distributor->SetLP(Mass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); } break; } case TBrakeValve::EP2: { WriteLog("XBT EP2"); - brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); - brakes.distributor->SetLP(Mass, brakes.maxPressureMass, brakes.maxCylinderPressure[1]); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor->SetLP(Mass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); break; } case TBrakeValve::EP1: { WriteLog("XBT EP1"); - brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); - brakes.distributor->SetLP(Mass, brakes.maxPressureMass, brakes.maxCylinderPressure[1]); - brakes.distributor->SetRM(brakes.rapidRatio); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor->SetLP(Mass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); + brakes.distributor->SetRM(brakes.config.rapidRatio); break; } case TBrakeValve::CV1: { WriteLog("XBT CV1"); - brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); break; } case TBrakeValve::CV1_L_TR: { WriteLog("XBT CV1_L_T"); - brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); break; } default: - brakes.distributor = std::make_shared(brakes.maxCylinderPressure[3], brakes.cylinders.radius, brakes.cylinders.stroke, brakes.valveVolume, brakes.cylinders.count, brakes.availableDelays, brakes.method, NAxles, brakes.blocksPerAxle); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); } - brakes.distributor->SetASBP(brakes.maxCylinderPressure[4]); - brakes.distributor->SetRV(brakes.rapidSpeed); + brakes.distributor->SetASBP(brakes.config.maxCylinderPressure[4]); + brakes.distributor->SetRV(brakes.config.rapidSpeed); } // the driver's handle and the local brake handle of the vehicle's kinds void physics::Vehicle::CreateBrakeHandles() { - switch (brakes.driverValveType) + switch (brakes.config.driverValveType) { using enum TBrakeHandle; case FV4a: @@ -356,14 +356,14 @@ void physics::Vehicle::CreateBrakeHandles() default: brakes.driverValve = std::make_shared(); } - brakes.driverValve->SetParams(brakes.driverValveSettings.automaticOverload, brakes.driverValveSettings.manualOverload, brakes.driverValveSettings.genericParameter1, brakes.driverValveSettings.genericParameter2, brakes.driverValveSettings.overloadMaxPressure, brakes.driverValveSettings.overloadPressureDecrease); + brakes.driverValve->SetParams(brakes.config.driverValveSettings.automaticOverload, brakes.config.driverValveSettings.manualOverload, brakes.config.driverValveSettings.genericParameter1, brakes.config.driverValveSettings.genericParameter2, brakes.config.driverValveSettings.overloadMaxPressure, brakes.config.driverValveSettings.overloadPressureDecrease); - switch (brakes.independentValveType) + switch (brakes.config.independentValveType) { case TBrakeHandle::FD1: { brakes.independentValve = std::make_shared(); - brakes.independentValve->Init(brakes.maxCylinderPressure[0]); + brakes.independentValve->Init(brakes.config.maxCylinderPressure[0]); if (TrainType == train_type::emu) { @@ -374,7 +374,7 @@ void physics::Vehicle::CreateBrakeHandles() case TBrakeHandle::Knorr: { brakes.independentValve = std::make_shared(); - brakes.independentValve->Init(brakes.maxCylinderPressure[0]); + brakes.independentValve->Init(brakes.config.maxCylinderPressure[0]); break; } default: @@ -385,16 +385,16 @@ void physics::Vehicle::CreateBrakeHandles() // the brake pipe, the main pipe and the spring brake's cylinder void physics::Vehicle::CreateBrakePipes() { - if (true == TestFlag(brakes.availableDelays, bdelay_G) && (false == TestFlag(brakes.availableDelays, bdelay_R) || Power > 1.0)) // ustalanie srednicy przewodu glownego (lokomotywa lub napędowy - brakes.pipeSection = 0.792; + if (true == TestFlag(brakes.config.availableDelays, bdelay_G) && (false == TestFlag(brakes.config.availableDelays, bdelay_R) || Power > 1.0)) // ustalanie srednicy przewodu glownego (lokomotywa lub napędowy + brakes.config.pipeSection = 0.792; else - brakes.pipeSection = 0.507; + brakes.config.pipeSection = 0.507; // WriteLog("SPG = " + FloatToStr(Spg)); brakePipe.reservoir = std::make_shared(); mainPipe.reservoir = std::make_shared(); // zabezpieczenie, bo sie PG wywala... :( - brakePipe.reservoir->CreateCap((std::max(Dim.L, 14.0) + 0.5) * brakes.pipeSection * 1); // dlugosc x przekroj x odejscia i takie tam - mainPipe.reservoir->CreateCap((std::max(Dim.L, 14.0) + 0.5) * brakes.pipeSection * 1); + brakePipe.reservoir->CreateCap((std::max(Dim.L, 14.0) + 0.5) * brakes.config.pipeSection * 1); // dlugosc x przekroj x odejscia i takie tam + mainPipe.reservoir->CreateCap((std::max(Dim.L, 14.0) + 0.5) * brakes.config.pipeSection * 1); if (!brakes.spring.cylinder) { brakes.spring.cylinder = std::make_shared(); @@ -447,19 +447,19 @@ void physics::Vehicle::SetReadyToDepart() void physics::Vehicle::SetBraked() { WriteLog("Braked"); - brakes.reservoirAir = brakes.valveVolume * brakes.maxCylinderPressure[3]; + brakes.reservoirAir = brakes.config.valveVolume * brakes.config.maxCylinderPressure[3]; air.Fill(air.config.mainReservoirVolume * air.compressor.config.minPressure * 0.55); /* ScndPipePress = 5.1; */ mainPipe.SetPressure(InitialScndPipePress(5.1)); - brakePipe.SetPressure(brakes.pipeLowPressure); - brakes.pipeCylinderPressure = brakes.maxCylinderPressure[3] * 0.5; - brakes.cylinderPressure = brakes.maxCylinderPressure[3] * 0.5; + brakePipe.SetPressure(brakes.config.pipeLowPressure); + brakes.pipeCylinderPressure = brakes.config.maxCylinderPressure[3] * 0.5; + brakes.cylinderPressure = brakes.config.maxCylinderPressure[3] * 0.5; brakes.independentPosition = 0.0; brakes.handlePosition = static_cast(brakes.driverValve->GetPos(bh_NP)); - brakes.pipeLimiterPressure = brakes.pipeLowPressure; - if (brakes.localKind == TLocalBrake::ManualBrake || brakes.hasHandBrake == true) + brakes.pipeLimiterPressure = brakes.config.pipeLowPressure; + if (brakes.config.localKind == TLocalBrake::ManualBrake || brakes.config.hasHandBrake == true) { IncManualBrakeLevel(ManualBrakePosNo); } diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index f6ab99ed5..3e2e8d468 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -1199,7 +1199,7 @@ double physics::Vehicle::InductionMotorBrakeRatio(double const ActiveInverters, // ustalanie współczynnika blendingu do luzowania hamulca PN if (inductionMotor.state.maxForce * Sign(V) * DirAbsolute < -1) { - PosRatio = -Sign(V) * DirAbsolute * inductionMotor.state.force / (inductionMotor.braking.maxForce * std::max(edBCP, std::max(0.01, brakes.distributor->GetEDBCP())) / brakes.maxCylinderPressure[0]); + PosRatio = -Sign(V) * DirAbsolute * inductionMotor.state.force / (inductionMotor.braking.maxForce * std::max(edBCP, std::max(0.01, brakes.distributor->GetEDBCP())) / brakes.config.maxCylinderPressure[0]); PosRatio = std::clamp(PosRatio, 0.0, 1.0); } else @@ -1225,13 +1225,13 @@ double physics::Vehicle::InductionMotorBrakeRatio(double const ActiveInverters, // 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 / brakes.maxCylinderPressure[0], 1.0)), AnPos) * vhRamp; - inductionMotor.state.forceDemand = -std::min(1.0, std::max(edLeverDemand, edBCP / brakes.maxCylinderPressure[0])); + PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / brakes.config.maxCylinderPressure[0], 1.0)), AnPos) * vhRamp; + inductionMotor.state.forceDemand = -std::min(1.0, std::max(edLeverDemand, edBCP / brakes.config.maxCylinderPressure[0])); } else { - PosRatio = -std::max(std::min(edBCP * 1.0 / brakes.maxCylinderPressure[0], 1.0), AnPos) * vhRamp; - inductionMotor.state.forceDemand = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / brakes.maxCylinderPressure[0])); + PosRatio = -std::max(std::min(edBCP * 1.0 / brakes.config.maxCylinderPressure[0], 1.0), AnPos) * vhRamp; + inductionMotor.state.forceDemand = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / brakes.config.maxCylinderPressure[0])); } } return PosRatio; diff --git a/physics/consistbraking.cpp b/physics/consistbraking.cpp index f8218ffd2..22b38570e 100644 --- a/physics/consistbraking.cpp +++ b/physics/consistbraking.cpp @@ -77,7 +77,7 @@ void physics::ConsistBrakeBlending::SetControl(Step &state, Vehicle &Lead, Input state.eimic = -1.0; Lead.SendCtrlToNext(VehicleCommand::integratedController, std::max(0., state.eimic), Lead.CabActive); state.LBR = std::max(-state.eimic, 0.); - state.eim_lb = Given.aiDriving || !Lead.brakes.independentTraxx ? 0 : Lead.eim_localbrake; + state.eim_lb = Given.aiDriving || !Lead.brakes.config.independentTraxx ? 0 : Lead.eim_localbrake; } // steps 1-2 of the blending: the masses and the most braking forces, pneumatic and ED, summed over the consist @@ -97,18 +97,18 @@ void physics::ConsistBrakeBlending::SumForces(Step &state, std::vectorbrakes.maxPressureMass - + ( vehicle->brakes.maxPressureMass > 1.0 ? + vehicle->brakes.config.maxPressureMass + + ( vehicle->brakes.config.maxPressureMass > 1.0 ? 0.0 : vehicle->Mass ) + vehicle->Mred; - auto const Nmax = ((vehicle->brakes.pressureToForce * vehicle->brakes.maxCylinderPressure[0] - - vehicle->brakes.cylinders.springForce) * - vehicle->brakes.cylinders.leverRatio[0] - - vehicle->brakes.cylinders.slackAdjusterForce) * - vehicle->brakes.cylinders.count * vehicle->brakes.cylinders.riggingEfficiency; + auto const Nmax = ((vehicle->brakes.config.pressureToForce * vehicle->brakes.config.maxCylinderPressure[0] - + vehicle->brakes.config.cylinders.springForce) * + vehicle->brakes.config.cylinders.leverRatio[0] - + vehicle->brakes.config.cylinders.slackAdjusterForce) * + vehicle->brakes.config.cylinders.count * vehicle->brakes.config.cylinders.riggingEfficiency; state.FmaxPN += Nmax * vehicle->brakes.distributor->GetFC( - Nmax / (vehicle->NAxles * vehicle->brakes.blocksPerAxle), + Nmax / (vehicle->NAxles * vehicle->brakes.config.blocksPerAxle), vehicle->brakes.blending.referenceSpeed) * 1000; // sila hamowania pn state.FmaxED += vehicle->lineBreaker.IsClosed() && vehicle->DirActive != 0 && vehicle->inductionMotor.inverterRatio == 1.0 && @@ -132,9 +132,9 @@ void physics::ConsistBrakeBlending::SumForces(Step &state, std::vector Lead.brakes.blending.minEdDemand - && ( Lead.brakes.driverValveType == TBrakeHandle::MHZ_EN57 ? + && ( Lead.brakes.config.driverValveType == TBrakeHandle::MHZ_EN57 ? (Lead.brakes.operatingMode & bom_MED) != 0 : Lead.EpFuse ) ) { state.FzadED = std::min( state.Fzad, state.FmaxED ); @@ -273,14 +273,14 @@ void physics::ConsistBrakeBlending::DistributeForces(Step &state, Vehicle const int i = 0; for (auto *vehicle : Consist) { - auto const Nmax = ((vehicle->brakes.pressureToForce * vehicle->brakes.maxCylinderPressure[0] - - vehicle->brakes.cylinders.springForce) * - vehicle->brakes.cylinders.leverRatio[0] - - vehicle->brakes.cylinders.slackAdjusterForce) * - vehicle->brakes.cylinders.count * vehicle->brakes.cylinders.riggingEfficiency; + auto const Nmax = ((vehicle->brakes.config.pressureToForce * vehicle->brakes.config.maxCylinderPressure[0] - + vehicle->brakes.config.cylinders.springForce) * + vehicle->brakes.config.cylinders.leverRatio[0] - + vehicle->brakes.config.cylinders.slackAdjusterForce) * + vehicle->brakes.config.cylinders.count * vehicle->brakes.config.cylinders.riggingEfficiency; FmaxEP[i] = Nmax * vehicle->brakes.distributor->GetFC( - Nmax / (vehicle->NAxles * vehicle->brakes.blocksPerAxle), + Nmax / (vehicle->NAxles * vehicle->brakes.config.blocksPerAxle), vehicle->brakes.blending.referenceSpeed) * 1000; // sila hamowania pn @@ -333,11 +333,11 @@ void physics::ConsistBrakeBlending::DistributeForces(Step &state, Vehicle const i = 0; for (auto *vehicle : Consist) { - float Nmax = ((vehicle->brakes.pressureToForce * vehicle->brakes.maxCylinderPressure[0] - - vehicle->brakes.cylinders.springForce) * - vehicle->brakes.cylinders.leverRatio[0] - - vehicle->brakes.cylinders.slackAdjusterForce) * - vehicle->brakes.cylinders.count * vehicle->brakes.cylinders.riggingEfficiency; + float Nmax = ((vehicle->brakes.config.pressureToForce * vehicle->brakes.config.maxCylinderPressure[0] - + vehicle->brakes.config.cylinders.springForce) * + vehicle->brakes.config.cylinders.leverRatio[0] - + vehicle->brakes.config.cylinders.slackAdjusterForce) * + vehicle->brakes.config.cylinders.count * vehicle->brakes.config.cylinders.riggingEfficiency; if (state.FrED > 0.1) vehicle->brakes.blending.epCorrectionTimer = 0; else @@ -346,23 +346,23 @@ void physics::ConsistBrakeBlending::DistributeForces(Step &state, Vehicle const float VelC = EPVC ? safe_clamp(vehicle->Vel, vehicle->brakes.blending.minSpeed, vehicle->brakes.blending.maxSpeed) : vehicle->brakes.blending.referenceSpeed;//korekcja EP po prędkości float FmaxPoj = Nmax * vehicle->brakes.distributor->GetFC( - Nmax / (vehicle->NAxles * vehicle->brakes.blocksPerAxle), VelC) * + Nmax / (vehicle->NAxles * vehicle->brakes.config.blocksPerAxle), VelC) * 1000; // sila hamowania pn vehicle->brakes.independentPositionEim = FzEP[i] / FmaxPoj; if (vehicle->brakes.independentPositionEim>0.009) - if (vehicle->brakes.pressureToForce * vehicle->brakes.cylinders.leverRatio[0] * - vehicle->brakes.maxCylinderPressure[0] != 0) + if (vehicle->brakes.config.pressureToForce * vehicle->brakes.config.cylinders.leverRatio[0] * + vehicle->brakes.config.maxCylinderPressure[0] != 0) { - float x = (vehicle->brakes.cylinders.slackAdjusterForce / vehicle->brakes.cylinders.leverRatio[0] + - vehicle->brakes.cylinders.springForce) / (vehicle->brakes.pressureToForce * - vehicle->brakes.maxCylinderPressure[0]); + float x = (vehicle->brakes.config.cylinders.slackAdjusterForce / vehicle->brakes.config.cylinders.leverRatio[0] + + vehicle->brakes.config.cylinders.springForce) / (vehicle->brakes.config.pressureToForce * + vehicle->brakes.config.maxCylinderPressure[0]); vehicle->brakes.independentPositionEim = x + (1 - x) * vehicle->brakes.independentPositionEim; } else vehicle->brakes.independentPositionEim = vehicle->brakes.independentPositionEim; else vehicle->brakes.independentPositionEim = 0; - if (vehicle->brakes.independentTraxx) + if (vehicle->brakes.config.independentTraxx) { vehicle->eim_localbrake = state.eim_lb; vehicle->brakes.independentPositionEim = std::max(vehicle->brakes.independentPositionEim, state.eim_lb); diff --git a/physics/vehicle.h b/physics/vehicle.h index c6e4030eb..4a1b9effa 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -1561,7 +1561,7 @@ class Vehicle // car, as the EN57 s car does). it's the vehicle type's, unlike the cab the scenario puts a driver in bool HasDriverCab() const { - return brakes.driverValveType != TBrakeHandle::NoHandle; + return brakes.config.driverValveType != TBrakeHandle::NoHandle; } // whether the cab command opening the main circuit opens it where the only cab switch of the circuit is the button // closing it: on a diesel that's the starter button, and the command is the one way to stop an engine whose fuel pump diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index 0e7c7a1bc..9f7f78057 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -145,46 +145,46 @@ std::vector parameters() { {"BearingType", [](auto const &M) { return M.BearingType; }}, {"ADist", [](auto const &M) { return M.ADist; }}, {"BDist", [](auto const &M) { return M.BDist; }}, - {"NBpA", [](auto const &M) { return M.brakes.blocksPerAxle; }}, + {"NBpA", [](auto const &M) { return M.brakes.config.blocksPerAxle; }}, {"SandCapacity", [](auto const &M) { return M.SandCapacity; }}, - {"BrakeSystem", [](auto const &M) { return static_cast(M.brakes.kind); }}, - {"BrakeValve", [](auto const &M) { return static_cast(M.brakes.distributorType); }}, - {"BrakeHandle", [](auto const &M) { return static_cast(M.brakes.driverValveType); }}, - {"BrakeLocHandle", [](auto const &M) { return static_cast(M.brakes.independentValveType); }}, - {"LocalBrake", [](auto const &M) { return static_cast(M.brakes.localKind); }}, - {"ASBType", [](auto const &M) { return M.brakes.antiSlipType; }}, - {"MaxBrakeForce", [](auto const &M) { return M.brakes.maxForce; }}, - {"P2FTrans", [](auto const &M) { return M.brakes.pressureToForce; }}, - {"BrakeMethod", [](auto const &M) { return M.brakes.method; }}, - {"HighPipePress", [](auto const &M) { return M.brakes.pipeHighPressure; }}, - {"LowPipePress", [](auto const &M) { return M.brakes.pipeLowPressure; }}, - {"DeltaPipePress", [](auto const &M) { return M.brakes.pipePressureRange; }}, + {"BrakeSystem", [](auto const &M) { return static_cast(M.brakes.config.kind); }}, + {"BrakeValve", [](auto const &M) { return static_cast(M.brakes.config.distributorType); }}, + {"BrakeHandle", [](auto const &M) { return static_cast(M.brakes.config.driverValveType); }}, + {"BrakeLocHandle", [](auto const &M) { return static_cast(M.brakes.config.independentValveType); }}, + {"LocalBrake", [](auto const &M) { return static_cast(M.brakes.config.localKind); }}, + {"ASBType", [](auto const &M) { return M.brakes.config.antiSlipType; }}, + {"MaxBrakeForce", [](auto const &M) { return M.brakes.config.maxForce; }}, + {"P2FTrans", [](auto const &M) { return M.brakes.config.pressureToForce; }}, + {"BrakeMethod", [](auto const &M) { return M.brakes.config.method; }}, + {"HighPipePress", [](auto const &M) { return M.brakes.config.pipeHighPressure; }}, + {"LowPipePress", [](auto const &M) { return M.brakes.config.pipeLowPressure; }}, + {"DeltaPipePress", [](auto const &M) { return M.brakes.config.pipePressureRange; }}, {"CntrlPipePress", [](auto const &M) { return M.brakes.controlReservoirPressure; }}, - {"BrakeVolume", [](auto const &M) { return M.brakes.cylinderVolume; }}, - {"BrakeVVolume", [](auto const &M) { return M.brakes.valveVolume; }}, + {"BrakeVolume", [](auto const &M) { return M.brakes.config.cylinderVolume; }}, + {"BrakeVVolume", [](auto const &M) { return M.brakes.config.valveVolume; }}, {"VeselVolume", [](auto const &M) { return M.air.config.mainReservoirVolume; }}, - {"BrakeCylNo", [](auto const &M) { return M.brakes.cylinders.count; }}, - {"BrakeCylRadius", [](auto const &M) { return M.brakes.cylinders.radius; }}, - {"BrakeCylDist", [](auto const &M) { return M.brakes.cylinders.stroke; }}, - {"BrakeCylSpring", [](auto const &M) { return M.brakes.cylinders.springForce; }}, - {"BrakeSlckAdj", [](auto const &M) { return M.brakes.cylinders.slackAdjusterForce; }}, - {"BrakeRigEff", [](auto const &M) { return M.brakes.cylinders.riggingEfficiency; }}, - {"RapidMult", [](auto const &M) { return M.brakes.rapidRatio; }}, - {"RapidVel", [](auto const &M) { return M.brakes.rapidSpeed; }}, - {"BrakeValveSize", [](auto const &M) { return M.brakes.distributorSize; }}, + {"BrakeCylNo", [](auto const &M) { return M.brakes.config.cylinders.count; }}, + {"BrakeCylRadius", [](auto const &M) { return M.brakes.config.cylinders.radius; }}, + {"BrakeCylDist", [](auto const &M) { return M.brakes.config.cylinders.stroke; }}, + {"BrakeCylSpring", [](auto const &M) { return M.brakes.config.cylinders.springForce; }}, + {"BrakeSlckAdj", [](auto const &M) { return M.brakes.config.cylinders.slackAdjusterForce; }}, + {"BrakeRigEff", [](auto const &M) { return M.brakes.config.cylinders.riggingEfficiency; }}, + {"RapidMult", [](auto const &M) { return M.brakes.config.rapidRatio; }}, + {"RapidVel", [](auto const &M) { return M.brakes.config.rapidSpeed; }}, + {"BrakeValveSize", [](auto const &M) { return M.brakes.config.distributorSize; }}, {"MinCompressor", [](auto const &M) { return M.air.compressor.config.minPressure; }}, {"MaxCompressor", [](auto const &M) { return M.air.compressor.config.maxPressure; }}, {"CompressorSpeed", [](auto const &M) { return M.air.compressor.config.speed; }}, {"EmergencyValveOn", [](auto const &M) { return M.brakes.emergencyValve.onPressure; }}, {"AirLeakRate", [](auto const &M) { return M.air.config.leakRate; }}, - {"BrakeCtrlPosNo", [](auto const &M) { return M.brakes.handlePositions; }}, + {"BrakeCtrlPosNo", [](auto const &M) { return M.brakes.config.handlePositions; }}, {"MainCtrlPosNo", [](auto const &M) { return M.MainCtrlPosNo; }}, {"ScndCtrlPosNo", [](auto const &M) { return M.ScndCtrlPosNo; }}, {"LightsPosNo", [](auto const &M) { return M.LightsPosNo; }}, - {"MBrake", [](auto const &M) { return M.brakes.hasHandBrake ? 1.0 : 0.0; }}, + {"MBrake", [](auto const &M) { return M.brakes.config.hasHandBrake ? 1.0 : 0.0; }}, {"StopBrakeDecc", [](auto const &M) { return M.brakes.holding.deceleration; }}, - {"BrakeDelays", [](auto const &M) { return M.brakes.availableDelays; }}, - {"BrakeOpModes", [](auto const &M) { return M.brakes.availableOperatingModes; }}, + {"BrakeDelays", [](auto const &M) { return M.brakes.config.availableDelays; }}, + {"BrakeOpModes", [](auto const &M) { return M.brakes.config.availableOperatingModes; }}, {"Imin", [](auto const &M) { return M.Imin; }}, {"Imax", [](auto const &M) { return M.Imax; }}, {"EIMCtrlType", [](auto const &M) { return M.EIMCtrlType; }}, @@ -192,10 +192,10 @@ std::vector parameters() { {"PantVolume", [](auto const &M) { return M.pantographAir.Volume(); }}, }; for (int i = 0; i < 5; ++i) { - result.emplace_back(std::format("MaxBrakePress{}", i), [i](auto const &M) { return M.brakes.maxCylinderPressure[i]; }); + result.emplace_back(std::format("MaxBrakePress{}", i), [i](auto const &M) { return M.brakes.config.maxCylinderPressure[i]; }); } for (int i = 0; i < 3; ++i) { - result.emplace_back(std::format("BrakeCylMult{}", i), [i](auto const &M) { return M.brakes.cylinders.leverRatio[i]; }); + result.emplace_back(std::format("BrakeCylMult{}", i), [i](auto const &M) { return M.brakes.config.cylinders.leverRatio[i]; }); } return result; } diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index cb2ad3c02..b3bf168c2 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -24,7 +24,7 @@ bool electric(physics::Vehicle const &M) { double max_brake_press(physics::Vehicle const &M) { auto result{0.0}; - for (auto const press : M.brakes.maxCylinderPressure) { + for (auto const press : M.brakes.config.maxCylinderPressure) { result = std::max(result, press); } return result; @@ -115,7 +115,7 @@ std::vector const &invariants() { }, [](auto const &M) { return values({{"V", M.V}, {"AccS", M.AccS}}); }}, {"hand brake applied, the wheels braked on the move", - [](auto const &M, double, auto const *) { return false == M.brakes.hasHandBrake || M.brakes.handBrakePosition == 0 || std::abs(M.V) < 0.5 || std::abs(M.Fb) > 0.0; }, + [](auto const &M, double, auto const *) { return false == M.brakes.config.hasHandBrake || M.brakes.handBrakePosition == 0 || std::abs(M.V) < 0.5 || std::abs(M.Fb) > 0.0; }, [](auto const &M) { return values({{"ManualBrakePos", M.brakes.handBrakePosition}, {"V", M.V}, {"Fb", M.Fb}}); }}, }; return rules; diff --git a/tests/unit/test_brake_cycle.cpp b/tests/unit/test_brake_cycle.cpp index 71db7a97d..342cbcf6b 100644 --- a/tests/unit/test_brake_cycle.cpp +++ b/tests/unit/test_brake_cycle.cpp @@ -79,7 +79,7 @@ TEST_CASE("brake cycle: every brake delay setting of the real vehicles") { test::reseed_random(); vehicle probe{definition::fiz(path)}; for (auto const delay : {bdelay_G, bdelay_P, bdelay_R, bdelay_R + bdelay_M, bdelay_G + bdelay_M}) { - if ((probe->brakes.availableDelays & delay) != delay || delay == probe->brakes.delaySetting) { + if ((probe->brakes.config.availableDelays & delay) != delay || delay == probe->brakes.delaySetting) { continue; } CAPTURE(delay); diff --git a/tests/unit/test_brake_handles.cpp b/tests/unit/test_brake_handles.cpp index d7b6ba077..d37ef677b 100644 --- a/tests/unit/test_brake_handles.cpp +++ b/tests/unit/test_brake_handles.cpp @@ -24,7 +24,7 @@ std::vector handle_channels() { // the vehicles with a driver's brake handle bool has_handle(vehicle &Vehicle) { - return Vehicle->brakes.handlePositions > 1; + return Vehicle->brakes.config.handlePositions > 1; } void hold(vehicle &Vehicle, test::trace &Trace, std::string const &Event, double Position, double Seconds) { @@ -171,7 +171,7 @@ void ready_knorr_ep(test::consist &Unit) { Unit.add(definition::fiz("en57_v1/6bai"), 1); Unit.add(definition::fiz("en57_v1/5bgb")); auto &cab{Unit[0]}; - REQUIRE(cab->brakes.driverValveType == TBrakeHandle::St113); + REQUIRE(cab->brakes.config.driverValveType == TBrakeHandle::St113); REQUIRE(cab->brakes.driverValve != nullptr); cab->BatterySwitch(true); cab->CabActivisation(); @@ -210,7 +210,7 @@ TEST_CASE("brake handles: the positions of the Knorr St113 EP brake") { CHECK(handle.GetPos(bh_RP) == doctest::Approx(0.0)); CHECK(ep_at(unit, 0.0) == doctest::Approx(-1.0)); // EP release CHECK(ep_at(unit, 1.0) == doctest::Approx(1.0)); // EP brake - CHECK(ep_at(unit, cab->brakes.handlePositions / 2) == doctest::Approx(0.0)); // lap, Num 5 + CHECK(ep_at(unit, cab->brakes.config.handlePositions / 2) == doctest::Approx(0.0)); // lap, Num 5 CHECK(ep_at(unit, handle.GetPos(bh_FB)) == doctest::Approx(0.0)); CHECK(ep_at(unit, handle.GetPos(bh_EPR)) == doctest::Approx(-1.0)); CHECK(ep_at(unit, handle.GetPos(bh_EPB)) == doctest::Approx(1.0)); @@ -281,7 +281,7 @@ struct st113_sample { std::vector st113_run() { test::reseed_random(); vehicle real{definition::fiz("en57_v1/6bai")}; - REQUIRE(real->brakes.driverValveType == TBrakeHandle::St113); + REQUIRE(real->brakes.config.driverValveType == TBrakeHandle::St113); REQUIRE(real->brakes.driverValve != nullptr); real.hold_main_reservoir(std::max(real->air.compressor.config.maxPressure, 8.0)); auto &handle{*real->brakes.driverValve}; diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp index d2800784b..e1281992b 100644 --- a/tests/unit/test_brake_pipe.cpp +++ b/tests/unit/test_brake_pipe.cpp @@ -22,8 +22,8 @@ void freight_train(test::consist &Train, int const Wagons) { for (int i = 0; i < Wagons; ++i) { auto &wagon{Train.add(definition::fiz("3wl_v2/3wl"))}; wagon->BrakeDelaySwitch(bdelay_G); - REQUIRE(wagon->brakes.distributorType == TBrakeValve::ESt3); - REQUIRE(wagon->brakes.pipeSection == doctest::Approx(0.792)); // the pipe of a freight wagon + REQUIRE(wagon->brakes.config.distributorType == TBrakeValve::ESt3); + REQUIRE(wagon->brakes.config.pipeSection == 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 } @@ -33,7 +33,7 @@ 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->brakes.pipeSection == doctest::Approx(0.507)); // the pipe of a passenger car + REQUIRE(car->brakes.config.pipeSection == doctest::Approx(0.507)); // the pipe of a passenger car } Train[0].hold_brake_pipe(5.0); } diff --git a/tests/unit/test_brakes.cpp b/tests/unit/test_brakes.cpp index 1541cb9d3..ed69a9a42 100644 --- a/tests/unit/test_brakes.cpp +++ b/tests/unit/test_brakes.cpp @@ -108,7 +108,7 @@ TEST_CASE("brakes: a dead EN57 hauled with the brake hose alone charges from the // a unit standing dead: no air anywhere, nothing in its main reservoir pipe for (std::size_t i = 1; i < train.size(); ++i) { auto &car{train[i].physics()}; - REQUIRE(car.brakes.distributorType == TBrakeValve::EP2); + REQUIRE(car.brakes.config.distributorType == TBrakeValve::EP2); car.brakes.distributor->ForceEmptiness(); car.brakePipe.reservoir->CreatePress(0.0); car.brakePipe.reservoir->Act(); diff --git a/tests/unit/test_cntrl.cpp b/tests/unit/test_cntrl.cpp index eba42f832..394b26d7a 100644 --- a/tests/unit/test_cntrl.cpp +++ b/tests/unit/test_cntrl.cpp @@ -9,13 +9,13 @@ using test::vehicle; TEST_CASE("cntrl: the brake delays of the settings come from BDelay1 to BDelay4") { vehicle wagon{definition::load("wagon").set("Cntrl", "BDelay1", 10.0).set("Cntrl", "BDelay2", 20.0).set("Cntrl", "BDelay3", 30.0).set("Cntrl", "BDelay4", 40.0)}; - CHECK(wagon->brakes.delays[0] == doctest::Approx(10.0)); + CHECK(wagon->brakes.config.delays[0] == doctest::Approx(10.0)); // the vehicle varies the others a little, by 0.83 to 0.9 (CheckLocomotiveParameters()) for (auto setting{1}; setting < 4; ++setting) { CAPTURE(setting); auto const given{10.0 * (setting + 1)}; - CHECK(wagon->brakes.delays[setting] >= 0.83 * given); - CHECK(wagon->brakes.delays[setting] <= 0.9 * given); + CHECK(wagon->brakes.config.delays[setting] >= 0.83 * given); + CHECK(wagon->brakes.config.delays[setting] <= 0.9 * given); } } diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp index 1ebcc03c9..c191fae53 100644 --- a/tests/unit/test_crew.cpp +++ b/tests/unit/test_crew.cpp @@ -300,7 +300,7 @@ TEST_CASE("crew: the power an integrated handle asked for goes when the driver l 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->brakes.kind == TBrakeSystem::Individual); + REQUIRE(bus->brakes.config.kind == TBrakeSystem::Individual); REQUIRE(bus->brakes.independentPosition == 0.0); bus->CabActivisation(); diff --git a/tests/unit/test_definition.cpp b/tests/unit/test_definition.cpp index 6c9deb7d3..0abcc824a 100644 --- a/tests/unit/test_definition.cpp +++ b/tests/unit/test_definition.cpp @@ -14,8 +14,8 @@ TEST_CASE("definition: the wagon from data/wagon.json loads with its values") { CHECK(wagon->Dim.L == doctest::Approx(26.8)); CHECK(wagon->WheelDiameter == doctest::Approx(0.96)); CHECK(wagon->NAxles == 4); - CHECK(wagon->brakes.maxCylinderPressure[3] == doctest::Approx(3.8)); - CHECK(wagon->brakes.kind == TBrakeSystem::Pneumatic); + CHECK(wagon->brakes.config.maxCylinderPressure[3] == doctest::Approx(3.8)); + CHECK(wagon->brakes.config.kind == TBrakeSystem::Pneumatic); } TEST_CASE("definition: keys set by the test reach the vehicle") { @@ -63,7 +63,7 @@ TEST_CASE("definition: lines the loader skips or trims: comments, a hash anywher REQUIRE(wagon.LoadFIZ_Text(crlf)); CHECK(wagon.Mass == doctest::Approx(42200.0)); CHECK(wagon.Vmax == doctest::Approx(120.0)); - CHECK(wagon.brakes.maxCylinderPressure[3] == doctest::Approx(3.8)); + CHECK(wagon.brakes.config.maxCylinderPressure[3] == doctest::Approx(3.8)); } TEST_CASE("definition: a compressor list, whose positions allow the compressor and scale its speed and limits") { diff --git a/tests/unit/test_drivingaid.cpp b/tests/unit/test_drivingaid.cpp index 9a4cbdea9..b12c80851 100644 --- a/tests/unit/test_drivingaid.cpp +++ b/tests/unit/test_drivingaid.cpp @@ -99,7 +99,7 @@ TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, 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->brakes.localKind == TLocalBrake::PneumaticBrake); + REQUIRE(elf->brakes.config.localKind == TLocalBrake::PneumaticBrake); auto const idle{read(elf, elf_cab)}; CHECK_FALSE(idle.show_local_brake); diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index c89d56ee5..7f11594f1 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -301,11 +301,11 @@ void hold(elf &Unit, bool Hold) { auto const force{Unit.cab().brakes.holding.deceleration * mass}; for (std::size_t i = 0; i < Unit.unit.size(); ++i) { auto &car{Unit.car(i)}; - auto const nmax{((car.brakes.pressureToForce * car.brakes.maxCylinderPressure[0] - car.brakes.cylinders.springForce) * car.brakes.cylinders.leverRatio[0] - car.brakes.cylinders.slackAdjusterForce) * car.brakes.cylinders.count * car.brakes.cylinders.riggingEfficiency}; - auto const fmax{nmax * car.brakes.distributor->GetFC(nmax / (car.NAxles * car.brakes.blocksPerAxle), car.brakes.blending.referenceSpeed) * 1000}; + auto const nmax{((car.brakes.config.pressureToForce * car.brakes.config.maxCylinderPressure[0] - car.brakes.config.cylinders.springForce) * car.brakes.config.cylinders.leverRatio[0] - car.brakes.config.cylinders.slackAdjusterForce) * car.brakes.config.cylinders.count * car.brakes.config.cylinders.riggingEfficiency}; + auto const fmax{nmax * car.brakes.distributor->GetFC(nmax / (car.NAxles * car.brakes.config.blocksPerAxle), car.brakes.blending.referenceSpeed) * 1000}; auto position{Hold ? force * car.NAxles / axles / fmax : 0.0}; if (position > 0.009) { - auto const slack{(car.brakes.cylinders.slackAdjusterForce / car.brakes.cylinders.leverRatio[0] + car.brakes.cylinders.springForce) / (car.brakes.pressureToForce * car.brakes.maxCylinderPressure[0])}; + auto const slack{(car.brakes.config.cylinders.slackAdjusterForce / car.brakes.config.cylinders.leverRatio[0] + car.brakes.config.cylinders.springForce) / (car.brakes.config.pressureToForce * car.brakes.config.maxCylinderPressure[0])}; position = slack + (1 - slack) * position; } else { diff --git a/tests/unit/test_est3al2_relay.cpp b/tests/unit/test_est3al2_relay.cpp index 6d3e60e85..b3f730558 100644 --- a/tests/unit/test_est3al2_relay.cpp +++ b/tests/unit/test_est3al2_relay.cpp @@ -64,7 +64,7 @@ struct times { times measure(int const Delay, int const Lever) { test::reseed_random(); vehicle wagon{fas_413s()}; - REQUIRE(wagon->brakes.distributorType == TBrakeValve::ESt3AL2); + REQUIRE(wagon->brakes.config.distributorType == TBrakeValve::ESt3AL2); if (wagon->brakes.delaySetting != Delay) { REQUIRE(wagon->BrakeDelaySwitch(Delay)); } diff --git a/tests/unit/test_fiz.cpp b/tests/unit/test_fiz.cpp index 54f7a1ac9..31087a141 100644 --- a/tests/unit/test_fiz.cpp +++ b/tests/unit/test_fiz.cpp @@ -40,7 +40,7 @@ TEST_CASE("fiz: changes made by a test reach the vehicle") { CHECK(vehicle{eu07}->Mass == doctest::Approx(80000.0)); CHECK(vehicle{definition{eu07}.set("Param", "M", 90000)}->Mass == doctest::Approx(90000.0)); // a key the file doesn't have is added to its section - CHECK(vehicle{definition{eu07}.set("Brake", "MaxBP", 3.5)}->brakes.maxCylinderPressure[3] == doctest::Approx(3.5)); + CHECK(vehicle{definition{eu07}.set("Brake", "MaxBP", 3.5)}->brakes.config.maxCylinderPressure[3] == doctest::Approx(3.5)); // removing a key brings its default back CHECK(vehicle{definition{eu07}.remove("Param", "Vmax")}->Vmax != doctest::Approx(125.0)); } diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index b9d678436..e764c5ba9 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -140,7 +140,7 @@ vehicle::vehicle(definition const &Definition, double Velocity, std::string cons if (driveractive) { m_physics->brakes.handlePosition = static_cast(std::floor(m_physics->brakes.driverValve->GetPos(Cab == 0 ? bh_NP : bh_RP))); // a driver keeps a vehicle on standby on its independent brake - if (Cab != 0 && m_physics->brakes.localKind != TLocalBrake::ManualBrake && Velocity < 1.0) { + if (Cab != 0 && m_physics->brakes.config.localKind != TLocalBrake::ManualBrake && Velocity < 1.0) { m_physics->IncLocalBrakeLevel(LocalBrakePosNo); if (m_physics->EIMCtrlEmergency) { m_physics->DecLocalBrakeLevel(1); diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index 507fca0b2..81b807301 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -104,7 +104,7 @@ void TController::Activation() if (pVehicle != initialvehicle) { // jeśli zmieniony został pojazd prowadzony ControllingSet(); // utworzenie połączenia do sterowanego pojazdu (może się zmienić) - silnikowy dla EZT - if( occupied->brakes.handlePositions > 0 + if( occupied->brakes.config.handlePositions > 0 && ( BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic ) ) { occupied->brakes.pipeLimiterPressure = occupied->brakePipe.Pressure(); @@ -177,7 +177,7 @@ void TController::AutoRewident() if( true == AIControllFlag ) { // if a human is in charge leave the brake mode up to them, otherwise do as you like for( int i = 1; i <= 8; i *= 2 ) { - if( ( occupied->brakes.availableOperatingModes & i ) > 0 ) { + if( ( occupied->brakes.config.availableOperatingModes & i ) > 0 ) { occupied->brakes.operatingMode = i; } } @@ -338,8 +338,8 @@ bool TController::CheckVehicles(DriverOrders user) fMass += p->physics->TotalMass; // dodanie masy łącznie z ładunkiem fVelMax = min_speed( fVelMax, p->physics->Vmax ); // ustalenie maksymalnej prędkości dla składu // reset oerlikon brakes consist flag as different type was detected - if( p->physics->brakes.subsystem != TBrakeSubSystem::ss_ESt - && p->physics->brakes.subsystem != TBrakeSubSystem::ss_LSt ) { + if( p->physics->brakes.config.subsystem != TBrakeSubSystem::ss_ESt + && p->physics->brakes.config.subsystem != TBrakeSubSystem::ss_LSt ) { drivingFlags.oerlikons = false; } p = p->Neighbour(dir); // pojazd podłączony od wskazanej strony @@ -659,7 +659,7 @@ void TController::ControllingSet() return; } occupied = pVehicle->physics; // domyślny skrót do obiektu parametrów - BrakeSystem = occupied->brakes.kind; // domyślny sposób hamowania + BrakeSystem = occupied->brakes.config.kind; // domyślny sposób hamowania mvControlling = pVehicle->FindPowered()->physics; // poszukiwanie członu sterowanego { auto *lookup { pVehicle->FindPantographCarrier() }; @@ -695,7 +695,7 @@ TController::determine_consist_state() { Ready = true; // wstępnie gotowy fReady = 0.0; // założenie, że odhamowany - IsConsistBraked = occupied->brakes.kind == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ? occupied->brakes.cylinderPressure > 2.0 : + IsConsistBraked = occupied->brakes.config.kind == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ? occupied->brakes.cylinderPressure > 2.0 : occupied->brakePipe.Pressure() < std::max(3.9, occupied->brakes.actualPressure.PipePressureVal) + 0.1; fAccGravity = 0.0; // przyspieszenie wynikające z pochylenia IsAnyCouplerStretched = false; @@ -716,11 +716,11 @@ TController::determine_consist_state() { while (p) { // sprawdzenie odhamowania wszystkich połączonych pojazdów auto *vehicle { p->physics }; - auto const bp { std::max( 0.0, vehicle->brakes.cylinderPressure - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->brakes.maxCylinderPressure[ 0 ] * vehicle->brakes.holding.deceleration : 0.0 ) ) }; + auto const bp { std::max( 0.0, vehicle->brakes.cylinderPressure - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->brakes.config.maxCylinderPressure[ 0 ] * vehicle->brakes.holding.deceleration : 0.0 ) ) }; momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); mostapplied = std::max( bp, mostapplied ); - if( ( vehicle->brakes.kind != TBrakeSystem::Individual ) - && ( vehicle->brakes.maxCylinderPressure[ 3 ] > 0.0 ) + if( ( vehicle->brakes.config.kind != TBrakeSystem::Individual ) + && ( vehicle->brakes.config.maxCylinderPressure[ 3 ] > 0.0 ) && ( false == TestFlag( vehicle->brakes.distributor->GetBrakeStatus(), b_dmg ) ) ) { // a brake cut out doesn't count chargelevel = std::min( { chargelevel, vehicle->brakePipe.Pressure(), vehicle->brakes.distributor->GetBRP() } ); } diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index 0fb94ba1d..793d182b2 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -66,7 +66,7 @@ TController::increase_train_brake() { } pos_corr = pos_corr / fMass * 2.5; - if (occupied->brakes.driverValveType == TBrakeHandle::FV4a) + if (occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) { pos_corr += occupied->brakes.driverValve->GetCP()*0.2; @@ -103,8 +103,8 @@ TController::increase_train_brake() { && AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting && ( fBrakeHeldTime > ( occupied->brakes.delaySetting > bdelay_G ? - occupied->brakes.delays[ 1 ] : - occupied->brakes.delays[ 3 ] ) + occupied->brakes.config.delays[ 1 ] : + occupied->brakes.config.delays[ 3 ] ) // a train falling further behind needs no full fill time to be seen not to get enough || ( ( brakingShortfall.value > 0.02 ) && ( fBrakeHeldTime > vehicle_ai::brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) { @@ -125,7 +125,7 @@ bool TController::IncBrake() BrakeSystem }; switch( bs ) { case TBrakeSystem::Individual: { - if( occupied->brakes.localKind == TLocalBrake::ManualBrake ) { + if( occupied->brakes.config.localKind == TLocalBrake::ManualBrake ) { OK = occupied->IncManualBrakeLevel( 1 + static_cast( std::floor( 0.5 + std::fabs( AccDesired ) ) ) ); } else { @@ -134,7 +134,7 @@ bool TController::IncBrake() break; } case TBrakeSystem::Pneumatic: { - if (bs != occupied->brakes.kind) + if (bs != occupied->brakes.config.kind) { while (occupied->brakes.operatingMode > bom_PN) { @@ -217,11 +217,11 @@ bool TController::IncBrake() break; } case TBrakeSystem::ElectroPneumatic: { - while( occupied->brakes.operatingMode << 1 <= occupied->brakes.availableOperatingModes ) { + while( occupied->brakes.operatingMode << 1 <= occupied->brakes.config.availableOperatingModes ) { occupied->brakes.operatingMode <<= 1; } if( occupied->EngineType == TEngineType::ElectricInductionMotor ) { - if (occupied->brakes.driverValveType == TBrakeHandle::MHZ_EN57) { + if (occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_EN57) { if (occupied->brakes.handlePosition < occupied->brakes.driverValve->GetPos(bh_FB)) OK = occupied->BrakeLevelAdd(1.0); } @@ -324,7 +324,7 @@ bool TController::DecBrake() { switch( bs ) { case TBrakeSystem::Individual: { auto const positionchange { 1 + std::floor( 0.5 + std::abs( AccDesired ) ) }; - OK = occupied->brakes.localKind == TLocalBrake::ManualBrake ? occupied->DecManualBrakeLevel(positionchange) : occupied->DecLocalBrakeLevel(positionchange); + OK = occupied->brakes.config.localKind == TLocalBrake::ManualBrake ? occupied->DecManualBrakeLevel(positionchange) : occupied->DecLocalBrakeLevel(positionchange); break; } case TBrakeSystem::Pneumatic: { @@ -382,7 +382,7 @@ bool TController::DecBrake() { } case TBrakeSystem::ElectroPneumatic: { if( occupied->EngineType == TEngineType::ElectricInductionMotor ) { - if( occupied->brakes.driverValveType == TBrakeHandle::MHZ_EN57 ) { + if( occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_EN57 ) { if( occupied->brakes.handlePosition > occupied->brakes.driverValve->GetPos( bh_RP ) ) { OK = occupied->BrakeLevelAdd( -1.0 ); } @@ -1122,7 +1122,7 @@ void TController::SetTimeControllers() { if (occupied->brakes.driverValve->Time) { - auto const pressuredifference { occupied->brakes.driverValve->GetCP() - ( occupied->brakes.pipeHighPressure - BrakeCtrlPosition * 0.25*occupied->brakes.pipePressureRange ) }; + auto const pressuredifference { occupied->brakes.driverValve->GetCP() - ( occupied->brakes.config.pipeHighPressure - BrakeCtrlPosition * 0.25*occupied->brakes.config.pipePressureRange ) }; if (BrakeCtrlPosition > 0 && pressuredifference > 0.05) occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_FB)); else if (BrakeCtrlPosition > 0 && pressuredifference < -0.05) @@ -1134,11 +1134,11 @@ void TController::SetTimeControllers() else if (BrakeCtrlPosition == -2) occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_NP)); } - if( occupied->brakes.driverValveType == TBrakeHandle::FV4a ) { + if( occupied->brakes.config.driverValveType == TBrakeHandle::FV4a ) { occupied->BrakeLevelSet( BrakeCtrlPosition ); } - if( occupied->brakes.driverValveType == TBrakeHandle::MHZ_K8P - || occupied->brakes.driverValveType == TBrakeHandle::MHZ_EN57 ) { + if( occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_K8P + || occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_EN57 ) { if( BrakeCtrlPosition == 0 ) { occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_RP ) ); } @@ -1322,7 +1322,7 @@ void TController::SetTimeControllers() } //6.2. Setting buttons for (int i = 0; i < 3; i++) { - occupied->UniversalBrakeButton(i, UniversalBrakeButtons & occupied->brakes.universalButtonActions[i]); + occupied->UniversalBrakeButton(i, UniversalBrakeButtons & occupied->brakes.config.universalButtonActions[i]); } }; diff --git a/vehicle/ai/driver.cpp b/vehicle/ai/driver.cpp index abd9f279e..11faa4ffe 100644 --- a/vehicle/ai/driver.cpp +++ b/vehicle/ai/driver.cpp @@ -130,7 +130,7 @@ TController::~TController() TBrakeSystem TController::consist_brake_system() const { - if( occupied->brakes.kind != TBrakeSystem::ElectroPneumatic ) { return occupied->brakes.kind; } + if( occupied->brakes.config.kind != TBrakeSystem::ElectroPneumatic ) { return occupied->brakes.config.kind; } auto isepcapable = true; if( pVehicles[ VehicleEnd::front ] != pVehicles[ VehicleEnd::rear ] ) { diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index 5233b6743..10c24d013 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -176,7 +176,7 @@ bool TController::PrepareEngine() } control_field_shunting(); // sync virtual brake state with the 'real' one - if( occupied->brakes.driverValveType != TBrakeHandle::NoHandle ) { + if( occupied->brakes.config.driverValveType != TBrakeHandle::NoHandle ) { std::unordered_map const brakepositions{ { static_cast( occupied->brakes.driverValve->GetPos( bh_RP ) ), gbh_RP }, { static_cast( occupied->brakes.driverValve->GetPos( bh_NP ) ), gbh_NP }, @@ -193,7 +193,7 @@ bool TController::PrepareEngine() } else if( ( occupied->brakes.handlePositionSmooth != occupied->brakes.driverValve->GetPos( bh_RP ) ) && ( ( false == occupied->brakes.driverValve->Time ) - || ( occupied->brakes.driverValve->GetCP() < occupied->brakes.pipeHighPressure - 0.05 ) ) ) { + || ( occupied->brakes.driverValve->GetCP() < occupied->brakes.config.pipeHighPressure - 0.05 ) ) ) { cue_action( driver_hint::trainbrakerelease ); } // sync spring brake state across consist @@ -325,8 +325,8 @@ bool TController::ReleaseEngine() { // activate parking brake // TBD: do it earlier? cue_action( driver_hint::springbrakeon ); - if( occupied->brakes.localKind == TLocalBrake::ManualBrake - || occupied->brakes.hasHandBrake == true ) { + if( occupied->brakes.config.localKind == TLocalBrake::ManualBrake + || occupied->brakes.config.hasHandBrake == true ) { cue_action( driver_hint::manualbrakon ); } // switch off remaining power diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp index aeae777f5..77bbcbd52 100644 --- a/vehicle/ai/force.cpp +++ b/vehicle/ai/force.cpp @@ -252,7 +252,7 @@ void TController::control_uphill_start() { if( uphillStart.toppingUp ) { return; } - if( ( occupied->brakes.localKind != TLocalBrake::ManualBrake ) + if( ( occupied->brakes.config.localKind != TLocalBrake::ManualBrake ) && ( occupied->brakes.independentPosition > 0.0 ) ) { cue_action( driver_hint::independentbrakerelease ); } @@ -287,7 +287,7 @@ bool TController::uphill_brake_top_up() { } auto const action { uphill_start::brake_top_up( uphillStart.brakeTopUp, trainbrakeforce, uphillStart.holdingForce, BrakeCtrlPosition, fBrakeHeldTime, - occupied->brakes.delays[ occupied->brakes.delaySetting > bdelay_G ? 1 : 3 ] ) }; + occupied->brakes.config.delays[ occupied->brakes.delaySetting > bdelay_G ? 1 : 3 ] ) }; if( action == uphill_start::top_up_action::none ) { return false; } @@ -322,7 +322,7 @@ void TController::secure_standing_train() { if( false == bHasRun ) { bBrakeChargeStart = true; } - if( occupied->brakes.localKind != TLocalBrake::ManualBrake ) { + if( occupied->brakes.config.localKind != TLocalBrake::ManualBrake ) { cue_action( driver_hint::independentbrakeapply ); } if( false == brake_charge::locomotive_brake_holds( locomotive_brake_force(), fMass * fAccGravity ) ) { @@ -344,12 +344,12 @@ void TController::secure_standing_train() { // 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( ( occupied->brakes.localKind == TLocalBrake::ManualBrake ) - || ( occupied->brakes.maxCylinderPressure[ 0 ] <= 0.0 ) ) { + if( ( occupied->brakes.config.localKind == TLocalBrake::ManualBrake ) + || ( occupied->brakes.config.maxCylinderPressure[ 0 ] <= 0.0 ) ) { return 0.0; } return brake_charge::locomotive_brake_force( - occupied->BrakeForceP( occupied->brakes.maxCylinderPressure[ 0 ], 0.0 ), + occupied->BrakeForceP( occupied->brakes.config.maxCylinderPressure[ 0 ], 0.0 ), occupied->TotalMassxg ); } @@ -499,7 +499,7 @@ void TController::control_braking_force() { // TODO: check whether brake delay variable still has any purpose cue_action(driver_hint::brakingforceincrease, // Ra: ten czas należy zmniejszyć, jeśli czas dojazdu do zatrzymania jest mniejszy - (3.0 + 0.5 * ((occupied->brakes.delaySetting > bdelay_G ? occupied->brakes.delays[1] : occupied->brakes.delays[3]) - 3.0)) * 0.5); // Ra: tymczasowo, bo przeżyna S1 + (3.0 + 0.5 * ((occupied->brakes.delaySetting > bdelay_G ? occupied->brakes.config.delays[1] : occupied->brakes.config.delays[3]) - 3.0)) * 0.5); // Ra: tymczasowo, bo przeżyna S1 } else if( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( AccDesired < 0.0 ) @@ -529,11 +529,11 @@ void TController::control_braking_force() { // sanity check to prevent unintended brake release on sharp slopes // TODO: check whether brake delay variable still has any purpose cue_action(driver_hint::brakingforcedecrease, - (occupied->brakes.delaySetting > bdelay_G ? occupied->brakes.delays[0] : occupied->brakes.delays[2]) / 3.0 * 0.5); // Ra: tymczasowo, bo przeżyna S1 + (occupied->brakes.delaySetting > bdelay_G ? occupied->brakes.config.delays[0] : occupied->brakes.config.delays[2]) / 3.0 * 0.5); // Ra: tymczasowo, bo przeżyna S1 } // uphill, the locomotive brake acts at once while the train brake of a long train takes many seconds to apply: // put it on as the train comes to a stand, and at once if the train has started to roll back - if( ( occupied->brakes.localKind != TLocalBrake::ManualBrake ) + if( ( occupied->brakes.config.localKind != TLocalBrake::ManualBrake ) && ( occupied->brakes.independentPosition < 1.0 ) && ( ( uphill_stop_hold() && ( std::abs( velocity ) < 3.0 ) // a train that has slowed down short of where it is to stop and is to pull up further does not get it @@ -567,7 +567,7 @@ void TController::control_braking_force() { void TController::apply_independent_brake_only() { - if( occupied->brakes.localKind != TLocalBrake::ManualBrake ) { + if( occupied->brakes.config.localKind != TLocalBrake::ManualBrake ) { if( false == occupied->ShuntMode // no need for independent brake if autobrake is active && is_equal(occupied->brakes.handlePositionSmooth, occupied->brakes.driverValve->GetPos(bh_RP), 0.2) ) { cue_action( driver_hint::independentbrakeapply ); @@ -587,11 +587,11 @@ void TController::control_releaser() { auto const hasreleaser { false == (is_dmu() || is_emu()) // TODO: a more refined test than rejecting these types wholesale - && ( occupied->brakes.driverValveType == TBrakeHandle::FV4a - || occupied->brakes.driverValveType == TBrakeHandle::MHZ_6P - || occupied->brakes.driverValveType == TBrakeHandle::MHZ_K5P - || occupied->brakes.driverValveType == TBrakeHandle::MHZ_K8P - || occupied->brakes.driverValveType == TBrakeHandle::M394 ) }; + && ( occupied->brakes.config.driverValveType == TBrakeHandle::FV4a + || occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_6P + || occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_K5P + || occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_K8P + || occupied->brakes.config.driverValveType == TBrakeHandle::M394 ) }; if( false == hasreleaser ) { return; } @@ -656,11 +656,11 @@ void TController::control_main_pipe() { // napełnianie uderzeniowe if( BrakeSystem != TBrakeSystem::Pneumatic ) { return; } - if( occupied->brakes.driverValveType == TBrakeHandle::FV4a - || occupied->brakes.driverValveType == TBrakeHandle::MHZ_6P - || occupied->brakes.driverValveType == TBrakeHandle::MHZ_K5P - || occupied->brakes.driverValveType == TBrakeHandle::MHZ_K8P - || occupied->brakes.driverValveType == TBrakeHandle::M394 ) { + if( occupied->brakes.config.driverValveType == TBrakeHandle::FV4a + || occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_6P + || occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_K5P + || occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_K8P + || occupied->brakes.config.driverValveType == TBrakeHandle::M394 ) { auto const departblocked { is_departure_blocked( DepartBlockedFSDelay ) }; if( (drivingFlags.oerlikons || true == IsCargoTrain || departblocked) && BrakeCtrlPosition == gbh_RP && AbsAccS < 0.03 && AccDesired > -0.03 && VelDesired - occupied->Vel > 2.0 && fReady > 0.35 && @@ -732,7 +732,7 @@ bool TController::is_brake_charging_done() const { return false; } return ElapsedTime - BrakeChargingStart > FSMaxTime - || consist_max_crp() > occupied->brakes.pipeHighPressure + FSOverchargeCRP + || consist_max_crp() > occupied->brakes.config.pipeHighPressure + FSOverchargeCRP || std::ranges::any_of( BrakeChargingPipeOverchargeStart, [this]( auto const &Vehicle ) { return ElapsedTime - Vehicle.second > FSOverchargeTime; } ); diff --git a/vehicle/ai/speed.cpp b/vehicle/ai/speed.cpp index 36f13e427..550b8819e 100644 --- a/vehicle/ai/speed.cpp +++ b/vehicle/ai/speed.cpp @@ -448,7 +448,7 @@ vehicle_ai::brake_response_horizon( physics::Vehicle const *Vehicle, TBrakeSyste // BrakeDelay holds the release and the application time in G, then the same two in P auto const delays { Vehicle->brakes.delaySetting > bdelay_G ? 0 : 2 }; auto const isrelease { Acceleration < 0.0 }; - horizon = std::max( horizon, 0.5 * Vehicle->brakes.delays[ delays + ( isrelease ? 0 : 1 ) ] ); + horizon = std::max( horizon, 0.5 * Vehicle->brakes.config.delays[ delays + ( isrelease ? 0 : 1 ) ] ); } return horizon; } @@ -506,7 +506,7 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { braking_curve::brake_acting( BrakeCtrlPosition, // IncLocalBrakeLevel() moves the independent brake handle on a vehicle without one too - ( occupied->brakes.localKind == TLocalBrake::PneumaticBrake || occupied->brakes.localKind == TLocalBrake::HydraulicBrake ) ? + ( occupied->brakes.config.localKind == TLocalBrake::PneumaticBrake || occupied->brakes.config.localKind == TLocalBrake::HydraulicBrake ) ? occupied->brakes.independentPosition : 0.0 ), vehicle_ai::brake_response_horizon( occupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), @@ -821,7 +821,7 @@ TController::adjust_desired_speed_for_braking_test() { if( ( brakeTest.stage == RunningBrakeTest::Stage::waiting ) && ( 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( occupied->brakes.driverValveType == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now + if( occupied->brakes.config.driverValveType == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now if( false == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { return; } // not applicable if( false == AIControllFlag ) { return; } // TBD: add notification about braking test and enable it for human driver as well? diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp index 6c5517cfd..0d17d4311 100644 --- a/vehicle/brakesetting.cpp +++ b/vehicle/brakesetting.cpp @@ -254,7 +254,7 @@ bool is_cut_out(physics::Vehicle const &Vehicle) { vehicle describe(physics::Vehicle const &Vehicle, bool const Driven) { vehicle described; - described.delays = Vehicle.brakes.availableDelays; + described.delays = Vehicle.brakes.config.availableDelays; // a locomotive has Power > 1, though it may be a dead one at the end of the train described.powered = Vehicle.Power >= 1.0; described.length = Vehicle.Dim.L; diff --git a/vehicle/cab/brakecommands.cpp b/vehicle/cab/brakecommands.cpp index 2e60ad77f..de4bac186 100644 --- a/vehicle/cab/brakecommands.cpp +++ b/vehicle/cab/brakecommands.cpp @@ -57,7 +57,7 @@ void TTrain::OnCommand_independentbrakeincrease(TTrain *Train, command_data cons // the pneumatic local brake directly, never piggy-backing on the joint controller auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->occupied->brakes.localKind != TLocalBrake::ManualBrake) + if (Train->occupied->brakes.config.localKind != TLocalBrake::ManualBrake) { if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->MainCtrlPos > 0) { @@ -83,7 +83,7 @@ void TTrain::OnCommand_independentbrakeincreasefast(TTrain *Train, command_data auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->occupied->brakes.localKind != TLocalBrake::ManualBrake) + if (Train->occupied->brakes.config.localKind != TLocalBrake::ManualBrake) { if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->MainCtrlPos > 0) { @@ -109,7 +109,7 @@ void TTrain::OnCommand_independentbrakedecrease(TTrain *Train, command_data cons auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->occupied->brakes.localKind != TLocalBrake::ManualBrake + if (Train->occupied->brakes.config.localKind != TLocalBrake::ManualBrake // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba // TODO: sort AI out so it doesn't do things it doesn't have equipment for || Train->occupied->brakes.independentPosition > 0) @@ -138,7 +138,7 @@ void TTrain::OnCommand_independentbrakedecreasefast(TTrain *Train, command_data auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->occupied->brakes.localKind != TLocalBrake::ManualBrake + if (Train->occupied->brakes.config.localKind != TLocalBrake::ManualBrake // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba // TODO: sort AI out so it doesn't do things it doesn't have equipment for || Train->occupied->brakes.independentPosition > 0) @@ -189,7 +189,7 @@ void TTrain::OnCommand_independentbrakebailoff(TTrain *Train, command_data const if (Train->controlled->TrainType != train_type::emu && (Train->controlled->EngineType == TEngineType::ElectricSeriesMotor || Train->controlled->EngineType == TEngineType::DieselElectric || Train->controlled->EngineType == TEngineType::ElectricInductionMotor) && - Train->occupied->brakes.handlePositions > 0) + Train->occupied->brakes.config.handlePositions > 0) { if (Command.action == GLFW_PRESS) @@ -295,17 +295,17 @@ void TTrain::OnCommand_universalbrakebutton3(TTrain *Train, command_data const & void TTrain::OnCommand_trainbrakeincrease(TTrain *Train, command_data const &Command) { - if (Command.action == GLFW_REPEAT && Train->occupied->brakes.driverValveType == TBrakeHandle::FV4a) - Train->occupied->BrakeLevelAdd(Global.brake_speed * Command.time_delta * Train->occupied->brakes.handlePositions); - else if (Command.action == GLFW_PRESS && Train->occupied->brakes.driverValveType != TBrakeHandle::FV4a) + if (Command.action == GLFW_REPEAT && Train->occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) + Train->occupied->BrakeLevelAdd(Global.brake_speed * Command.time_delta * Train->occupied->brakes.config.handlePositions); + else if (Command.action == GLFW_PRESS && Train->occupied->brakes.config.driverValveType != TBrakeHandle::FV4a) Train->set_train_brake(Train->occupied->brakes.handlePositionSmooth + Global.fBrakeStep); } void TTrain::OnCommand_trainbrakedecrease(TTrain *Train, command_data const &Command) { - if (Command.action == GLFW_REPEAT && Train->occupied->brakes.driverValveType == TBrakeHandle::FV4a) - Train->occupied->BrakeLevelAdd(-Global.brake_speed * Command.time_delta * Train->occupied->brakes.handlePositions); - else if (Command.action == GLFW_PRESS && Train->occupied->brakes.driverValveType != TBrakeHandle::FV4a) + if (Command.action == GLFW_REPEAT && Train->occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) + Train->occupied->BrakeLevelAdd(-Global.brake_speed * Command.time_delta * Train->occupied->brakes.config.handlePositions); + else if (Command.action == GLFW_PRESS && Train->occupied->brakes.config.driverValveType != TBrakeHandle::FV4a) Train->set_train_brake(Train->occupied->brakes.handlePositionSmooth - Global.fBrakeStep); else if (Command.action == GLFW_RELEASE) { @@ -370,7 +370,7 @@ void TTrain::OnCommand_trainbrakeservice(TTrain *Train, command_data const &Comm if (Command.action == GLFW_PRESS) { - Train->set_train_brake(Train->occupied->brakes.handlePositions / 2 + (Train->occupied->brakes.driverValveType == TBrakeHandle::FV4a ? 1 : 0)); + Train->set_train_brake(Train->occupied->brakes.config.handlePositions / 2 + (Train->occupied->brakes.config.driverValveType == TBrakeHandle::FV4a ? 1 : 0)); } } @@ -380,7 +380,7 @@ void TTrain::OnCommand_trainbrakefullservice(TTrain *Train, command_data const & if (Command.action == GLFW_PRESS) { - Train->set_train_brake(Train->occupied->brakes.handlePositions - 1); + Train->set_train_brake(Train->occupied->brakes.config.handlePositions - 1); } } @@ -416,7 +416,7 @@ void TTrain::OnCommand_trainbrakebasepressureincrease(TTrain *Train, command_dat if (Command.action != GLFW_RELEASE) { - if (Train->occupied->brakes.driverValveType == TBrakeHandle::FV4a) + if (Train->occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) { Train->occupied->brakes.handleCapPosition = std::clamp(Train->occupied->brakes.handleCapPosition - 0.01, -1.5, 2.0); } @@ -433,7 +433,7 @@ void TTrain::OnCommand_trainbrakebasepressuredecrease(TTrain *Train, command_dat if (Command.action != GLFW_RELEASE) { - if (Train->occupied->brakes.driverValveType == TBrakeHandle::FV4a) + if (Train->occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) { Train->occupied->brakes.handleCapPosition = std::clamp(Train->occupied->brakes.handleCapPosition + 0.01, -1.5, 2.0); } @@ -484,7 +484,7 @@ void TTrain::OnCommand_manualbrakeincrease(TTrain *Train, command_data const &Co return; } - if (vehicle->physics->brakes.localKind == TLocalBrake::ManualBrake || vehicle->physics->brakes.hasHandBrake == true) + if (vehicle->physics->brakes.config.localKind == TLocalBrake::ManualBrake || vehicle->physics->brakes.config.hasHandBrake == true) { vehicle->physics->IncManualBrakeLevel(1); @@ -504,7 +504,7 @@ void TTrain::OnCommand_manualbrakedecrease(TTrain *Train, command_data const &Co return; } - if (vehicle->physics->brakes.localKind == TLocalBrake::ManualBrake || vehicle->physics->brakes.hasHandBrake == true) + if (vehicle->physics->brakes.config.localKind == TLocalBrake::ManualBrake || vehicle->physics->brakes.config.hasHandBrake == true) { vehicle->physics->DecManualBrakeLevel(1); @@ -566,7 +566,7 @@ void TTrain::OnCommand_wheelspinbrakeactivate(TTrain *Train, command_data const return; } - if (Train->occupied->brakes.kind != TBrakeSystem::ElectroPneumatic) + if (Train->occupied->brakes.config.kind != TBrakeSystem::ElectroPneumatic) { // standard behaviour if (Command.action == GLFW_PRESS) @@ -592,7 +592,7 @@ void TTrain::OnCommand_wheelspinbrakeactivate(TTrain *Train, command_data const // the EP fuse is the cab car's (Ctrl+Z switches occupied's), checked by SwitchEPBrake with the rest of // the control's supply - if (Train->occupied->brakes.driverValveType == TBrakeHandle::St113) + if (Train->occupied->brakes.config.driverValveType == TBrakeHandle::St113) { Train->occupied->SwitchEPBrake(1); } @@ -763,7 +763,7 @@ void TTrain::OnCommand_trainbrakeoperationmodeincrease(TTrain *Train, command_da { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action == GLFW_PRESS && (Train->occupied->brakes.operatingMode << 1 & Train->occupied->brakes.availableOperatingModes) != 0) + if (Command.action == GLFW_PRESS && (Train->occupied->brakes.operatingMode << 1 & Train->occupied->brakes.config.availableOperatingModes) != 0) { // next mode Train->occupied->brakes.operatingMode <<= 1; @@ -776,7 +776,7 @@ void TTrain::OnCommand_trainbrakeoperationmodedecrease(TTrain *Train, command_da { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action == GLFW_PRESS && (Train->occupied->brakes.operatingMode >> 1 & Train->occupied->brakes.availableOperatingModes) != 0) + if (Command.action == GLFW_PRESS && (Train->occupied->brakes.operatingMode >> 1 & Train->occupied->brakes.config.availableOperatingModes) != 0) { // previous mode Train->occupied->brakes.operatingMode >>= 1; diff --git a/vehicle/cab/sounds.cpp b/vehicle/cab/sounds.cpp index d893fd457..305f19c34 100644 --- a/vehicle/cab/sounds.cpp +++ b/vehicle/cab/sounds.cpp @@ -102,7 +102,7 @@ void TTrain::update_sounds(double const Deltatime) // McZapkie-280302 - syczenie // TODO: softer volume reduction than plain abrupt stop, perhaps as reusable wrapper? - if (occupied->brakes.driverValveType == TBrakeHandle::FV4a || occupied->brakes.driverValveType == TBrakeHandle::FVel6) + if (occupied->brakes.config.driverValveType == TBrakeHandle::FV4a || occupied->brakes.config.driverValveType == TBrakeHandle::FVel6) { // upuszczanie z PG if (rsHiss) @@ -219,7 +219,7 @@ void TTrain::update_sounds(double const Deltatime) { auto const brakeforceratio{ - std::clamp(occupied->brakes.unitForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles * std::max(1, occupied->brakes.blocksPerAxle))), 0.0, 1.0)}; + std::clamp(occupied->brakes.unitForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles * std::max(1, occupied->brakes.config.blocksPerAxle))), 0.0, 1.0)}; // HACK: in external view mute the sound rather than stop it, in case there's an opening bookend it'd (re)play on sound restart after returning inside volume = FreeFlyModeFlag ? 0.0 : rsBrake->m_amplitudeoffset + std::sqrt(brakeforceratio * std::lerp(0.4, 1.0, occupied->Vel / (1 + occupied->Vmax))) * rsBrake->m_amplitudefactor; rsBrake->pitch(static_cast(rsBrake->m_frequencyoffset + occupied->Vel * rsBrake->m_frequencyfactor)); @@ -457,7 +457,7 @@ void TTrain::update_sounds_runningnoise(sound_source &Sound) if (std::abs(occupied->nrot) > 0.01) { // hamulce wzmagaja halas - auto const brakeforceratio{(std::clamp(occupied->brakes.unitForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles * std::max(1, occupied->brakes.blocksPerAxle))), 0.0, 1.0))}; + auto const brakeforceratio{(std::clamp(occupied->brakes.unitForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles * std::max(1, occupied->brakes.config.blocksPerAxle))), 0.0, 1.0))}; volume *= 1 + 0.125 * brakeforceratio; } diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 7c7546b0a..2660be874 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -439,7 +439,7 @@ TTrain::state_t TTrain::get_state() const bool TTrain::is_eztoer() const { - return controlled->TrainType == train_type::emu && occupied->brakes.subsystem == TBrakeSubSystem::ss_ESt && controlled->lowVoltage.Is24vAvailable() == true && controlled->EpFuse == true && + return controlled->TrainType == train_type::emu && occupied->brakes.config.subsystem == TBrakeSubSystem::ss_ESt && controlled->lowVoltage.Is24vAvailable() == true && controlled->EpFuse == true && controlled->DirActive != 0; // od yB } @@ -483,7 +483,7 @@ void TTrain::zero_charging_train_brake() using enum TBrakeHandle; if (occupied->brakes.handlePosition == -1 && DynamicObject->Controller != AIdriver && Global.iFeedbackMode < 3 && - (occupied->brakes.driverValveType == FVel6 || occupied->brakes.driverValveType == MHZ_EN57 || occupied->brakes.driverValveType == MHZ_K8P)) + (occupied->brakes.config.driverValveType == FVel6 || occupied->brakes.config.driverValveType == MHZ_EN57 || occupied->brakes.config.driverValveType == MHZ_K8P)) { // Odskakiwanie hamulce EP set_train_brake(0); diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 9aaba532c..ff508079e 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -109,7 +109,7 @@ bool TTrain::Update(double const Deltatime) updateCabLightLevels(); // anti slip system activation, maintained while the control button is down - if (occupied->brakes.kind != TBrakeSystem::ElectroPneumatic && ggAntiSlipButton.GetDesiredValue() > 0.95) + if (occupied->brakes.config.kind != TBrakeSystem::ElectroPneumatic && ggAntiSlipButton.GetDesiredValue() > 0.95) { controlled->AntiSlippingBrake(); } @@ -1276,19 +1276,19 @@ void TTrain::updateBrakeControllers() false && Global.fCalibrateIn[0][1] != 0.0) // nie blokujemy AI { // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba // Firleju: dlatego kasujemy i zastepujemy funkcją w Console - if (occupied->brakes.driverValveType == TBrakeHandle::FV4a) + if (occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) { double b = Console::AnalogCalibrateGet(0); b = b * 8.0 - 2.0; - b = safe_clamp(b, -2.0, (double)occupied->brakes.handlePositions); // przycięcie zmiennej do granic + b = safe_clamp(b, -2.0, (double)occupied->brakes.config.handlePositions); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia occupied->BrakeLevelSet(b); } - else if (occupied->brakes.driverValveType == TBrakeHandle::FVel6) // może można usunąć ograniczenie do FV4a i FVel6? + else if (occupied->brakes.config.driverValveType == TBrakeHandle::FVel6) // może można usunąć ograniczenie do FV4a i FVel6? { double b = Console::AnalogCalibrateGet(0); b = b * 7.0 - 1.0; - b = safe_clamp(b, -1.0, (double)occupied->brakes.handlePositions); // przycięcie zmiennej do granic + b = safe_clamp(b, -1.0, (double)occupied->brakes.config.handlePositions); // przycięcie zmiennej do granic ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia occupied->BrakeLevelSet(b); } @@ -1315,7 +1315,7 @@ void TTrain::updateBrakeControllers() { #ifdef _WIN32 if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag // nie blokujemy AI - && occupied->brakes.independentValveType == TBrakeHandle::FD1 && Global.iFeedbackMode == 4 && Global.fCalibrateIn[0][1] != 0.0) + && occupied->brakes.config.independentValveType == TBrakeHandle::FD1 && Global.iFeedbackMode == 4 && Global.fCalibrateIn[0][1] != 0.0) { // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba // Firleju: dlatego kasujemy i zastepujemy funkcją w Console diff --git a/vehicle/crew.cpp b/vehicle/crew.cpp index 5897dd5cb..8032cd750 100644 --- a/vehicle/crew.cpp +++ b/vehicle/crew.cpp @@ -119,8 +119,8 @@ void secure(physics::Vehicle &Occupied, physics::Vehicle &Controlling) { // the emergency position vents the brake pipe whatever the brake mode, and with nobody in the cab too Occupied.BrakeLevelSet(Occupied.brakes.driverValve->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.brakes.kind == TBrakeSystem::Individual) { - if (Occupied.brakes.localKind == TLocalBrake::ManualBrake) { + if (Occupied.brakes.config.kind == TBrakeSystem::Individual) { + if (Occupied.brakes.config.localKind == TLocalBrake::ManualBrake) { Occupied.IncManualBrakeLevel(ManualBrakePosNo); } else { diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index 2857bdaf3..8f21dd575 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -277,7 +277,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" // NOTE: with more than one driver in the consist this is likely to go awery, since all but one will be sent to sleep // TBD, TODO: have the virtual helper release independent brakes during consist check? if( DriverType != "" ) { - if( physics->brakes.localKind != TLocalBrake::ManualBrake ) { + if( physics->brakes.config.localKind != TLocalBrake::ManualBrake ) { if( fVel < 1.0 ) { physics->IncLocalBrakeLevel( LocalBrakePosNo ); if ( physics->EIMCtrlEmergency ) { @@ -369,28 +369,28 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" physics->brakes.distributor->ForceEmptiness(); physics->brakes.distributor->SetBrakeStatus( physics->brakes.distributor->GetBrakeStatus() | b_dmg ); // wylacz } - if (physics->brakes.cylinders.leverRatio[2] * physics->brakes.cylinders.leverRatio[1] > + if (physics->brakes.config.cylinders.leverRatio[2] * physics->brakes.config.cylinders.leverRatio[1] > 0.01) // jesli jest nastawiacz mechaniczny PL { float rnd = Random(100); if (rnd < 20) // losowanie 20/100 usrednienie { - physics->brakes.cylinders.leverRatio[2] = physics->brakes.cylinders.leverRatio[1] = - (physics->brakes.cylinders.leverRatio[2] + physics->brakes.cylinders.leverRatio[1]) / + physics->brakes.config.cylinders.leverRatio[2] = physics->brakes.config.cylinders.leverRatio[1] = + (physics->brakes.config.cylinders.leverRatio[2] + physics->brakes.config.cylinders.leverRatio[1]) / 2; } else if (rnd < 70) // losowanie 70/100-20/100 oslabienie { - physics->brakes.cylinders.leverRatio[1] = physics->brakes.cylinders.leverRatio[1] * 0.50; - physics->brakes.cylinders.leverRatio[2] = physics->brakes.cylinders.leverRatio[2] * 0.75; + physics->brakes.config.cylinders.leverRatio[1] = physics->brakes.config.cylinders.leverRatio[1] * 0.50; + physics->brakes.config.cylinders.leverRatio[2] = physics->brakes.config.cylinders.leverRatio[2] * 0.75; } else if (rnd < 80) // losowanie 80/100-70/100 tylko prozny { - physics->brakes.cylinders.leverRatio[2] = physics->brakes.cylinders.leverRatio[1]; + physics->brakes.config.cylinders.leverRatio[2] = physics->brakes.config.cylinders.leverRatio[1]; } else // tylko ladowny { - physics->brakes.cylinders.leverRatio[1] = physics->brakes.cylinders.leverRatio[2]; + physics->brakes.config.cylinders.leverRatio[1] = physics->brakes.config.cylinders.leverRatio[2]; } } } diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index 4eca3f008..ee0fd0fde 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -79,7 +79,7 @@ void TDynamicObject::RenderSounds() { // brake system and braking sounds: // brake cylinder piston - auto const brakepressureratio { std::max( 0.0, physics->brakes.cylinderPressure ) / std::max( 1.0, physics->brakes.maxCylinderPressure[ 3 ] ) }; + auto const brakepressureratio { std::max( 0.0, physics->brakes.cylinderPressure ) / std::max( 1.0, physics->brakes.config.maxCylinderPressure[ 3 ] ) }; renderBrakeCylinderSounds( brakepressureratio ); renderEpBrakeSounds( dt ); renderEmergencyBrakeSound(); @@ -233,7 +233,7 @@ void TDynamicObject::renderBrakeCylinderSounds( double const brakepressureratio } // actual sound playback auto const quantizedratio { static_cast( 15 * brakepressureratio ) }; - auto const lastbrakepressureratio { std::max( 0.f, m_lastbrakepressure ) / std::max( 1.0, physics->brakes.maxCylinderPressure[ 3 ] ) }; + auto const lastbrakepressureratio { std::max( 0.f, m_lastbrakepressure ) / std::max( 1.0, physics->brakes.config.maxCylinderPressure[ 3 ] ) }; auto const quantizedratiochange { quantizedratio - static_cast( 15 * lastbrakepressureratio ) }; if( quantizedratiochange > 0 ) { m_brakecylinderpistonadvance @@ -257,10 +257,10 @@ void TDynamicObject::renderBrakeCylinderSounds( double const brakepressureratio void TDynamicObject::renderEpBrakeSounds( double const dt ) { // epbrake - epcompact - if (physics->brakes.kind == TBrakeSystem::ElectroPneumatic && physics->brakes.independentValve) { - auto const epbrakepressureratio{ std::min( std::max( 0.0, physics->brakes.independentValve->GetCP() ) / std::max( 1.0, physics->brakes.maxCylinderPressure[0] ), + if (physics->brakes.config.kind == TBrakeSystem::ElectroPneumatic && physics->brakes.independentValve) { + auto const epbrakepressureratio{ std::min( std::max( 0.0, physics->brakes.independentValve->GetCP() ) / std::max( 1.0, physics->brakes.config.maxCylinderPressure[0] ), m_epbrakepressurechangedectimer > -1.0f ? - std::max( physics->brakes.independentPositionEim, physics->brakes.distributor->GetEDBCP() / physics->brakes.maxCylinderPressure[3]) : + std::max( physics->brakes.independentPositionEim, physics->brakes.distributor->GetEDBCP() / physics->brakes.config.maxCylinderPressure[3]) : 1.0 ) }; if ( m_lastepbrakepressure != -1.f ) { // HACK: potentially reset playback of opening bookend sounds @@ -274,7 +274,7 @@ void TDynamicObject::renderEpBrakeSounds( double const dt ) { m_epbrakepressurechangedectimer += dt; // actual sound playback auto const epquantizedratio{ static_cast( 50 * epbrakepressureratio) }; - auto const lastepbrakepressureratio { std::max( 0.f, m_lastepbrakepressure ) / std::max( 1.0, physics->brakes.maxCylinderPressure[0] ) }; + auto const lastepbrakepressureratio { std::max( 0.f, m_lastepbrakepressure ) / std::max( 1.0, physics->brakes.config.maxCylinderPressure[0] ) }; auto const epquantizedratiochange { epquantizedratio - static_cast( 50 * lastepbrakepressureratio ) }; if ( epquantizedratiochange > 0 && m_epbrakepressurechangeinctimer > 0.05f) { m_epbrakepressureincrease @@ -296,7 +296,7 @@ void TDynamicObject::renderEpBrakeSounds( double const dt ) { } if ( m_epbrakepressurechangeinctimer == 0 || m_epbrakepressurechangedectimer == 0 ) m_lastepbrakepressure = std::min( physics->brakes.independentValve->GetCP(), - physics->brakes.independentPositionEim * std::max( 1.0, physics->brakes.maxCylinderPressure[0] ) ); + physics->brakes.independentPositionEim * std::max( 1.0, physics->brakes.config.maxCylinderPressure[0] ) ); } } @@ -403,7 +403,7 @@ double TDynamicObject::renderBrakeFrictionSounds( double const dt ) { brakeforceratio = std::clamp( - physics->brakes.unitForce / std::max( 1.0, physics->BrakeForceR( 1.0, physics->Vel ) / ( physics->NAxles * std::max( 1, physics->brakes.blocksPerAxle ) ) ), + physics->brakes.unitForce / std::max( 1.0, physics->BrakeForceR( 1.0, physics->Vel ) / ( physics->NAxles * std::max( 1, physics->brakes.config.blocksPerAxle ) ) ), 0.0, 1.0 ); rsBrake .pitch( rsBrake.m_frequencyoffset + physics->Vel * rsBrake.m_frequencyfactor ) From d28b908ca4993126778aa5e7409919f74162fdd2 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 10:43:31 +0100 Subject: [PATCH 15/30] refactor(render): the renderer reads a vehicle through TDynamicObject, not its physics No file of rendering/ includes physics/vehicle.h any more. What the renderers read of a vehicle comes through a few queries of TDynamicObject (vehicle/dynamic/lights.cpp): its dimensions, its speed, its active cab, the light of its compartments, the adapters of its couplers, the lights switched on at an end, the low voltage for them, and the multiplier and the colour of its headlights. The shares of the speed and the opacity of the exhaust smoke (ExhaustScales()) move out of the particles into the vehicle, as they are. The headlights pick their multiplier once, by the dimming and the high beam switches, where the light array repeated the same four branches twice; the light of a switched off end still goes to zero as before. --- rendering/common/locallights.cpp | 3 +- rendering/common/localshadows.cpp | 3 +- rendering/common/scenewalk.cpp | 5 +- rendering/common/screenreflections.cpp | 3 +- rendering/common/windscreenwater.cpp | 5 +- rendering/lightarray.cpp | 40 ++++------------ rendering/opengl46/opengl46renderer.cpp | 9 ++-- rendering/particles.cpp | 18 +------- rendering/vulkan14/vulkan14frame.cpp | 9 ++-- vehicle/DynObj.h | 17 +++++++ vehicle/dynamic/lights.cpp | 61 +++++++++++++++++++++++++ 11 files changed, 102 insertions(+), 71 deletions(-) diff --git a/rendering/common/locallights.cpp b/rendering/common/locallights.cpp index 524dbb6e4..e138be067 100644 --- a/rendering/common/locallights.cpp +++ b/rendering/common/locallights.cpp @@ -29,7 +29,6 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Train.h" #include "simulation/simulation.h" #include "rendering/geometrybank.h" -#include "physics/vehicle.h" namespace { @@ -374,7 +373,7 @@ void gfx::local_lights::gather_vehicle(TDynamicObject *Vehicle, glm::dvec3 const { auto const &name{section.compartment->pName}; cabsection &= (name.size() >= 4) && name.starts_with("cab"); - auto const level{section.light_level * (cabsection ? 1.f : Vehicle->physics->CompartmentLights.intensity)}; + auto const level{section.light_level * (cabsection ? 1.f : Vehicle->CompartmentLightIntensity())}; if ((level <= 0.f) || (Global.fLuminance > section.compartment->fLight) || (section.compartment->iVisible == 0)) { continue; diff --git a/rendering/common/localshadows.cpp b/rendering/common/localshadows.cpp index 7e0d780c1..867473ed1 100644 --- a/rendering/common/localshadows.cpp +++ b/rendering/common/localshadows.cpp @@ -18,7 +18,6 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "vehicle/Train.h" #include "rendering/common/skyocclusion.h" -#include "physics/vehicle.h" namespace gfx { @@ -584,7 +583,7 @@ std::vector const &local_shadows::pick_headli if (std::max(beam.r, std::max(beam.g, beam.b)) <= 0.f) continue; // the part of the beam the shadows are cast in: from the end of the vehicle to the reach ahead of it - auto const &dimensions{light.owner->physics->Dim}; + auto const &dimensions{light.owner->Dimensions()}; auto const radius{range * 0.5 + std::max(dimensions.W, dimensions.H) + 2.0}; auto const centre{light.position + glm::dvec3{light.direction} * (range * 0.5 + 2.0)}; if (glm::length(centre - camera) - radius > range) diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index de01564f4..515379f6b 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -30,7 +30,6 @@ http://mozilla.org/MPL/2.0/. #include "model/AnimModel.h" #include "model/Model3d.h" #include "rendering/common/skyocclusion.h" -#include "physics/vehicle.h" #include #include #include @@ -295,8 +294,8 @@ bool scene_walk::Render_coupler_adapter( TDynamicObject *Dynamic, float const Sq auto const position { glm::dvec3 { 0.f, - Dynamic->physics->Couplers[ End ].adapter_height, - ( Dynamic->physics->Couplers[ End ].adapter_length + Dynamic->physics->Dim.L * 0.5 ) * ( End == VehicleEnd::front ? 1 : -1 ) } }; + Dynamic->CouplerAdapterHeight( End ), + ( Dynamic->CouplerAdapterLength( End ) + Dynamic->Dimensions().L * 0.5 ) * ( End == VehicleEnd::front ? 1 : -1 ) } }; auto const angle { glm::vec3{ 0, diff --git a/rendering/common/screenreflections.cpp b/rendering/common/screenreflections.cpp index e519b21ff..c730d97bd 100644 --- a/rendering/common/screenreflections.cpp +++ b/rendering/common/screenreflections.cpp @@ -13,7 +13,6 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "gl/ubo.h" #include "utilities/Globals.h" -#include "physics/vehicle.h" namespace { @@ -60,7 +59,7 @@ void gfx::screen_reflections::begin_frame(glm::mat4 const &Projection, glm::dmat { m_reprojectioncab = glm::mat4{m_history.projection * glm::dmat4{m_history.view} * m_history.cab * glm::inverse(m_current.cab) * toworld}; // the vehicle stands on the origin of its model, along z, up to its height - auto const &dimensions{Cab->physics->Dim}; + auto const &dimensions{Cab->Dimensions()}; glm::dvec3 const lower{-0.5 * dimensions.W - CAB_BOX_MARGIN, -CAB_BOX_MARGIN, -0.5 * dimensions.L - CAB_BOX_MARGIN}; glm::dvec3 const upper{0.5 * dimensions.W + CAB_BOX_MARGIN, dimensions.H + CAB_BOX_MARGIN, 0.5 * dimensions.L + CAB_BOX_MARGIN}; auto const centre{0.5 * (lower + upper)}; diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index 619b6bf33..0a1746645 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -19,7 +19,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "vehicle/DynObj.h" #include "vehicle/Train.h" -#include "physics/vehicle.h" namespace gfx { @@ -340,7 +339,7 @@ void windscreen_water::update(double const Seconds) // the blades of the wipers of the vehicle, as the glasses read them (the channels of the mask follow the wipers of the cab // the vehicle is driven from) glm::vec4 blades{-1.f}; - if (auto const cabactive{vehicle->physics->CabActive}; cabactive != 0) + if (auto const cabactive{vehicle->ActiveCab()}; cabactive != 0) { auto const count{static_cast(vehicle->dWiperPos.size())}; for (int i = 0; i < 4; ++i) @@ -356,7 +355,7 @@ void windscreen_water::update(double const Seconds) auto const toworld{glm::dmat3{vehicle->mMatrix}}; auto const tomodel{glm::inverse(toworld)}; auto const up{glm::normalize(glm::vec3{tomodel * glm::dvec3{0.0, 1.0, 0.0}})}; - auto const air{glm::vec3{tomodel * (glm::dvec3{simulation::Environment.wind()} * WIND_SHARE - vehicle->VectorFront() * vehicle->physics->V)}}; + auto const air{glm::vec3{tomodel * (glm::dvec3{simulation::Environment.wind()} * WIND_SHARE - vehicle->VectorFront() * vehicle->Speed())}}; auto const heavy{std::clamp(Global.Overcast - 1.f, 0.f, 1.f)}; auto const snow{Global.Weather == "snow:"}; auto const fall{snow ? SNOW_FALL : RAIN_FALL}; diff --git a/rendering/lightarray.cpp b/rendering/lightarray.cpp index 01ff98ee0..bfa20349a 100644 --- a/rendering/lightarray.cpp +++ b/rendering/lightarray.cpp @@ -16,7 +16,6 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "rendering/lightarray.h" #include "vehicle/DynObj.h" -#include "physics/vehicle.h" void light_array::insert( TDynamicObject const *Owner ) { @@ -52,11 +51,10 @@ light_array::update() { light.direction.z = -light.direction.z; } // determine intensity of this light set - if( ( true == light.owner->physics->lowVoltage.Is24vAvailable() ) - || ( true == light.owner->physics->lowVoltage.Is110vAvailable() ) ) { + if( true == light.owner->LowVoltagePowered() ) { // with power on, the intensity depends on the state of activated switches // first we cross-check the list of enabled lights with the lights installed in the vehicle... - auto const lights { light.owner->physics->iLights[ light.index ] & light.owner->LightList( static_cast( light.index ) ) }; + auto const lights { light.owner->LightsSwitchedOn( static_cast( light.index ) ) & light.owner->LightList( static_cast( light.index ) ) }; // ...then check their individual state light.count = 0 + ( ( lights & light::headlight_left ) ? 1 : 0 ) @@ -70,18 +68,11 @@ light_array::update() { bool isEnabled = EndOf( light.index ) == VehicleEnd::front ? !light.owner->HeadlightsAoff : !light.owner->HeadlightsBoff; light.intensity = std::max(0.0f, std::log((float)light.count + 1.0f)); - if (light.owner->DimHeadlights && !light.owner->HighBeamLights && isEnabled) // tylko przyciemnione - light.intensity *= static_cast(light.owner->physics->dimMultiplier); - else if (!light.owner->DimHeadlights && !light.owner->HighBeamLights && isEnabled) // normalne - light.intensity *= static_cast(light.owner->physics->normMultiplier); - else if (light.owner->DimHeadlights && light.owner->HighBeamLights && isEnabled) // przyciemnione dlugie - light.intensity *= static_cast(light.owner->physics->highDimMultiplier); - else if (!light.owner->DimHeadlights && light.owner->HighBeamLights && isEnabled) // dlugie zwykle - light.intensity *= static_cast(light.owner->physics->highMultiplier); - else if (!isEnabled) - { + auto const multiplier{light.owner->HeadlightsMultiplier()}; + if (isEnabled) + light.intensity *= static_cast(multiplier); + else light.intensity = 0.0f; - } // TBD, TODO: intensity can be affected further by other factors light.state = { @@ -89,24 +80,9 @@ light_array::update() { ( ( lights & light::headlight_upper ) ? 1.f : 0.f ), ( ( lights & light::headlight_right | light::highbeamlight_right) ? 1.f : 0.f ) }; - light.color = { - static_cast(light.owner->physics->refR) / 255.0f, - static_cast(light.owner->physics->refG) / 255.0f, - static_cast(light.owner->physics->refB) / 255.0f - }; + light.color = light.owner->HeadlightsColor(); - if (light.owner->DimHeadlights && !light.owner->HighBeamLights) // tylko przyciemnione - light.state *= light.owner->physics->dimMultiplier; - else if (!light.owner->DimHeadlights && !light.owner->HighBeamLights) // normalne - light.state *= light.owner->physics->normMultiplier; - else if (light.owner->DimHeadlights && light.owner->HighBeamLights) // przyciemnione dlugie - light.state *= light.owner->physics->highDimMultiplier; - else if (!light.owner->DimHeadlights && light.owner->HighBeamLights) // dlugie zwykle - light.state *= light.owner->physics->highMultiplier; - else if (!isEnabled) - { - light.state = glm::vec3{0.f}; - } + light.state *= multiplier; } else { light.intensity = 0.0f; diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index e1b65aa44..a79680f96 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -29,7 +29,6 @@ http://mozilla.org/MPL/2.0/. #include "rendering/opengl46/opengl46geometrybank.h" #include "rendering/screenshot.h" #include "rendering/editoroverlay.h" -#include "physics/vehicle.h" #include "vehicle/DynObj.h" #include @@ -1682,16 +1681,16 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) // vehicle (V is along the front of the vehicle) glm::dvec3 air{glm::dvec3{simulation::Environment.wind()} * 0.5}; if (TDynamicObject const *owner = Global.pCamera.m_owner) - air -= owner->VectorFront() * owner->physics->V; + air -= owner->VectorFront() * owner->Speed(); scene_ubs.rain_wind = glm::vec4{glm::vec3{air}, 0.f}; } - if (TDynamicObject const *owner = Global.pCamera.m_owner; owner && !!owner->physics->CabActive) + if (TDynamicObject const *owner = Global.pCamera.m_owner; owner && !!owner->ActiveCab()) { for (int i = 0; i < 4; ++i) { if (i < owner->dWiperPos.size()) { - int index = owner->physics->CabActive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; + int index = owner->ActiveCab() > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; scene_ubs.wiper_pos[i] = owner->dWiperPos[index]; if (owner->dWiperPos[index] > 0. && owner->wiperDirection[index]) { @@ -6761,7 +6760,7 @@ void opengl46_renderer::Render_lamp_shadow(std::size_t const Slot, bool const Ve void opengl46_renderer::Headlight_Projector(light_array::light_record const &Light, glm::dvec3 &Position, glm::mat3 &Rotation, glm::mat4 &Projection, float &Near, float &Fieldofview) { - auto const &ownerdimensions{Light.owner->physics->Dim}; + auto const &ownerdimensions{Light.owner->Dimensions()}; auto const up{static_cast(Light.owner->VectorUp())}; auto const size{static_cast(std::max(ownerdimensions.W, ownerdimensions.H) * 1.0)}; // ensure square ratio auto const cone{5.f}; diff --git a/rendering/particles.cpp b/rendering/particles.cpp index c0245be12..07e96d6b9 100644 --- a/rendering/particles.cpp +++ b/rendering/particles.cpp @@ -16,7 +16,6 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationenvironment.h" #include "utilities/Logs.h" #include "vehicle/smoke.h" -#include "physics/vehicle.h" #include "vehicle/DynObj.h" @@ -346,22 +345,7 @@ smoke_source::launch_scales( float &Velocity, float &Opacity ) const { Opacity = 1.f; if( m_ownertype != owner_type::vehicle ) { return; } - Opacity = static_cast(m_owner.vehicle->physics->diesel.fill); - if (m_owner.vehicle->physics->EngineType == TEngineType::DieselElectric) - { - if (m_owner.vehicle->physics->diesel.spinningUp == true) - { - Velocity = static_cast(0.38*(((m_owner.vehicle->physics->enrot)/2)*0.5)); // / m_owner.vehicle->physics->diesel.fill *0.01)) ; - - } - else - { - - Velocity = static_cast((((m_owner.vehicle->physics->enrot)/60)*0.6) * (m_owner.vehicle->physics->EnginePower *0.03)); // / m_owner.vehicle->physics->diesel.fill *0.01)) ; - //Particle.velocity *= m_owner.vehicle->GetVelocity(); // / m_owner.vehicle->physics->diesel.fill *0.01)) ; - } - - } + m_owner.vehicle->ExhaustScales( Velocity, Opacity ); } // updates state of provided particle and bounding box. returns: true if particle is still alive afterwards, false otherwise diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 1b802f3d5..b723551ca 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -32,7 +32,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/utilities.h" #include "utilities/color.h" -#include "physics/vehicle.h" #include @@ -1563,16 +1562,16 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) // vehicle (V is along the front of the vehicle) glm::dvec3 air{glm::dvec3{simulation::Environment.wind()} * 0.5}; if (TDynamicObject const *owner = Global.pCamera.m_owner) - air -= owner->VectorFront() * owner->physics->V; + air -= owner->VectorFront() * owner->Speed(); scene_ubs.rain_wind = glm::vec4{glm::vec3{air}, 0.f}; } - if (TDynamicObject const *owner = Global.pCamera.m_owner; owner && !!owner->physics->CabActive) + if (TDynamicObject const *owner = Global.pCamera.m_owner; owner && !!owner->ActiveCab()) { for (int i = 0; i < 4; ++i) { if (i < owner->dWiperPos.size()) { - int index = owner->physics->CabActive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; + int index = owner->ActiveCab() > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; scene_ubs.wiper_pos[i] = owner->dWiperPos[index]; if (owner->dWiperPos[index] > 0. && owner->wiperDirection[index]) { @@ -4153,7 +4152,7 @@ void vulkan14_renderer::write_local_light(gl::light_element &Light, gfx::local_l void vulkan14_renderer::headlight_projector(light_array::light_record const &Light, glm::dvec3 &Position, glm::mat3 &Rotation, glm::mat4 &Projection, float &Near, float &Fieldofview) { - auto const &ownerdimensions{Light.owner->physics->Dim}; + auto const &ownerdimensions{Light.owner->Dimensions()}; auto const up{static_cast(Light.owner->VectorUp())}; auto const size{static_cast(std::max(ownerdimensions.W, ownerdimensions.H) * 1.0)}; auto const cone{5.f}; diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 0e670f1d2..4566e17f0 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -902,6 +902,23 @@ public: double GetVelocity() const; double GetLength() const; double GetWidth() const; + // what the renderer reads of the physics of the vehicle (vehicle/dynamic/lights.cpp), so that it doesn't reach into it + TDimension const &Dimensions() const; + double Speed() const; // along the vehicle, signed [m/s] + int ActiveCab() const; // the cab the vehicle is driven from: 1 the front one, -1 the rear one, 0 none + float CompartmentLightIntensity() const; + double CouplerAdapterHeight( VehicleEnd End ) const; + double CouplerAdapterLength( VehicleEnd End ) const; + // the shares of the launch velocity and of the opacity of the smoke of the engine's exhaust, from the engine + void ExhaustScales( float &Velocity, float &Opacity ) const; + // the low voltage circuits have their power, for the lights + bool LowVoltagePowered() const; + // the lights switched on at an end, as the bits of light:: + int LightsSwitchedOn( VehicleEnd End ) const; + // the factor of the intensity of the headlights by the dimming and the high beam switches (DimHeadlights, HighBeamLights) + double HeadlightsMultiplier() const; + // the colour of the headlights, 0..1 + glm::vec3 HeadlightsColor() const; double radius() const; // calculates distance between event-starting axle and front of the vehicle double tracing_offset() const; diff --git a/vehicle/dynamic/lights.cpp b/vehicle/dynamic/lights.cpp index 663469aa9..8479de79f 100644 --- a/vehicle/dynamic/lights.cpp +++ b/vehicle/dynamic/lights.cpp @@ -250,3 +250,64 @@ bool TDynamicObject::has_signal_on( VehicleEnd const Side, int const Pattern ) c */ return physics->iLights[Side] == (Pattern & iInventory[Side]); } + +TDimension const &TDynamicObject::Dimensions() const { + return physics->Dim; +} + +double TDynamicObject::Speed() const { + return physics->V; +} + +int TDynamicObject::ActiveCab() const { + return physics->CabActive; +} + +float TDynamicObject::CompartmentLightIntensity() const { + return physics->CompartmentLights.intensity; +} + +double TDynamicObject::CouplerAdapterHeight( VehicleEnd const End ) const { + return physics->Couplers[ End ].adapter_height; +} + +double TDynamicObject::CouplerAdapterLength( VehicleEnd const End ) const { + return physics->Couplers[ End ].adapter_length; +} + +void TDynamicObject::ExhaustScales( float &Velocity, float &Opacity ) const { + Opacity = static_cast(physics->diesel.fill); + if (physics->EngineType == TEngineType::DieselElectric) + { + if (physics->diesel.spinningUp == true) + { + Velocity = static_cast(0.38*(((physics->enrot)/2)*0.5)); + } + else + { + Velocity = static_cast((((physics->enrot)/60)*0.6) * (physics->EnginePower *0.03)); + } + } +} + +bool TDynamicObject::LowVoltagePowered() const { + return ( true == physics->lowVoltage.Is24vAvailable() ) || ( true == physics->lowVoltage.Is110vAvailable() ); +} + +int TDynamicObject::LightsSwitchedOn( VehicleEnd const End ) const { + return physics->iLights[ End ]; +} + +double TDynamicObject::HeadlightsMultiplier() const { + if( DimHeadlights && !HighBeamLights ) { return physics->dimMultiplier; } // tylko przyciemnione + if( !DimHeadlights && !HighBeamLights ) { return physics->normMultiplier; } // normalne + if( DimHeadlights && HighBeamLights ) { return physics->highDimMultiplier; } // przyciemnione dlugie + return physics->highMultiplier; // dlugie zwykle +} + +glm::vec3 TDynamicObject::HeadlightsColor() const { + return { + static_cast(physics->refR) / 255.0f, + static_cast(physics->refG) / 255.0f, + static_cast(physics->refB) / 255.0f }; +} From 6aa6b077bfc12fee17ddcd8bf6839d97421cee00 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sun, 29 Nov 2026 10:48:12 +0100 Subject: [PATCH 16/30] ci: Sonar input without compiling; no AVX2 for master only; unit tests in the AVX2 build Build (the input of the SonarQube Cloud analysis): the analyzer needs the compile commands and the headers, not the objects, so the job no longer compiles under the Build Wrapper. CMake writes compile_commands.json at configure time (CMAKE_EXPORT_COMPILE_COMMANDS), together with the headers the project generates; glslang's build_info.h is made by its own small target. The database goes where sonar.yml reads it (bw-output/), so the trusted workflow is unchanged. build/CMakeFiles is packed now: it holds cmake_pch.hxx, which the commands include. Build binaries: the variant without AVX2 is built for master only (pushes to master, pull requests into master, i.e. staging into master) and by a manual run; branch downloads have the AVX2 build and point to build-master for the other one. A pull request into master from this repository builds again (both variants, the merge), as the check before a release. The variant without AVX2 builds no unit tests (-DWITH_TESTS=OFF, no lua51.dll): they run in the AVX2 build of the same commit. The matrix comes from the `changes` job. --- .github/workflows/build.yml | 29 +++++++------ .github/workflows/build_bin.yml | 75 +++++++++++++++++++++------------ 2 files changed, 65 insertions(+), 39 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 758b4c8d5..8ce3f1569 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -24,7 +24,7 @@ concurrency: jobs: build: - name: Build under Build Wrapper + name: Compilation database for SonarQube Cloud runs-on: ubuntu-24.04 permissions: contents: read @@ -76,23 +76,27 @@ jobs: ref/glm/glm/gtx/string_cast.inl grep -n "std::string format(const char\* message" ref/glm/glm/gtx/string_cast.inl - - name: Install SonarQube Cloud Build Wrapper - uses: SonarSource/sonarqube-scan-action/install-build-wrapper@fd88b7d7ccbaefd23d8f36f73b59db7a3d246602 # v6.0.0 - + # The analyzer needs the compile command of every file and the headers they include, not the objects: the + # compilation database CMake writes at configure time is enough, so nothing is compiled here. The headers the + # project generates (version_info.h, the editor icons) are written by the configure step too. - name: Configure (CMake) run: | cmake -S . -B build \ -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ -DWITH_BETTER_RENDERER=OFF \ -DWITH_ZMQ=OFF -DWITH_OPENVR=OFF -DUSE_LTO=OFF \ -DCMAKE_CXX_FLAGS="-Wno-attributes -fno-inline-functions-called-once" \ -DPython3_EXECUTABLE="$(which python3)" - - name: Build under Build Wrapper + # glslang writes its build_info.h at build time; its sources are excluded from the analysis, but the target + # is cheap and makes the include available should a header of ours reach it + - name: Compilation database run: | - build-wrapper-linux-x86-64 \ - --out-dir "${BUILD_WRAPPER_OUT_DIR}" \ - cmake --build build --config Release -j"$(nproc)" + cmake --build build --target glslang-build-info || echo "no glslang-build-info target, nothing generated" + mkdir -p "${BUILD_WRAPPER_OUT_DIR}" + cp build/compile_commands.json "${BUILD_WRAPPER_OUT_DIR}/compile_commands.json" + echo "$(grep -c '"file"' "${BUILD_WRAPPER_OUT_DIR}/compile_commands.json") compile commands" # Metadata the trusted workflow needs to identify the PR. # Treated as UNVERIFIED input there and re-checked against the API. @@ -109,13 +113,14 @@ jobs: printf '%s\n' "$PR_HEAD_SHA" > .sonar-meta/head_sha printf '%s\n' "$COMMIT_SHA" > .sonar-meta/sha - # The C/C++ analyzer needs the sources AND the build-wrapper output. - # compile_commands.json holds absolute paths, so the trusted workflow must - # unpack this at the same $GITHUB_WORKSPACE path — same repo, so it matches. + # The C/C++ analyzer needs the sources AND the compilation database (kept in bw-output/, where the + # trusted workflow reads it). compile_commands.json holds absolute paths, so the trusted workflow must + # unpack this at the same $GITHUB_WORKSPACE path — same repo, so it matches. build/CMakeFiles stays in: + # with nothing compiled it is small, and it holds cmake_pch.hxx, which every command of the targets with + # the precompiled header includes (-include). - name: Pack analysis input run: | tar -czf /tmp/workspace.tar.gz \ - --exclude='./build/CMakeFiles' \ --exclude='*.o' \ --exclude='*.a' \ --exclude='*.so' \ diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index c2bfe2e64..ca6087363 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -30,12 +30,18 @@ jobs: # Every push to a branch of this repository runs this workflow, and a pull request from such a branch would run it # once more for the same commit. The push run builds and publishes the download of the branch, so the pull request # run of a branch of this repository builds nothing (the merge with the base is compiled by the Build and Coverage - # workflows); a pull request from a fork has no push run here and builds as before. A push that changes only + # workflows), except a pull request into master (staging into master): that is the check before a release, of the + # merge, with both variants. A pull request from a fork has no push run here and builds as before. A push that changes only # documentation or the data of the scenario tests (which the binaries don't contain) builds nothing either: the # download of the branch stays at its last build, of the same binaries. Pushes to staging and master and manual runs # always build. The checks are job-level conditions, not `paths-ignore` or `branches-ignore` on the trigger: a skipped # job counts as passed, a workflow that doesn't start would leave a required check pending for ever (none is - # required today). Anything this job can't decide builds. + # required today; a skipped matrix job shows under its unexpanded name, `${{ matrix.variant.name }}`). Anything + # this job can't decide builds. + # + # The variant without AVX2 (CPUs older than Haswell, 2013) is the same sources with one compiler switch: it is built + # for master only (pushes to master, pull requests into master, so every staging into master) and by a manual run. + # It builds no unit tests: they run in the AVX2 build of the same commit. changes: name: Whether to build runs-on: ubuntu-24.04 @@ -45,6 +51,8 @@ jobs: pull-requests: read outputs: build: ${{ steps.decide.outputs.build }} + variants: ${{ steps.decide.outputs.variants }} + noavx2: ${{ steps.decide.outputs.noavx2 }} steps: - name: Decide from the event and the changed files id: decide @@ -57,10 +65,23 @@ jobs: BEFORE: ${{ github.event.before }} PR_NUMBER: ${{ github.event.pull_request.number }} PR_HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }} + BASE_REF: ${{ github.base_ref }} run: | + avx2='{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON","tests":true}' + noavx2='{"name":"No AVX2","suffix":"noavx2","cmake_flags":"-DENABLE_AVX2=OFF -DWITH_TESTS=OFF","tests":false}' + if [ "$EVENT_NAME" = workflow_dispatch ] \ + || { [ "$EVENT_NAME" = push ] && [ "$REF" = refs/heads/master ]; } \ + || { [ "$EVENT_NAME" = pull_request ] && [ "$BASE_REF" = master ]; }; then + echo "variants=[$avx2,$noavx2]" >> "$GITHUB_OUTPUT" + echo "noavx2=true" >> "$GITHUB_OUTPUT" + else + echo "variants=[$avx2]" >> "$GITHUB_OUTPUT" + echo "noavx2=false" >> "$GITHUB_OUTPUT" + fi build() { echo "$1"; echo "build=true" >> "$GITHUB_OUTPUT"; exit 0; } case "$EVENT_NAME" in pull_request) + [ "$BASE_REF" != master ] || build "A pull request into master, building the merge." if [ "$PR_HEAD_REPO" = "$REPO" ]; then echo "A branch of this repository: its push run builds this commit." echo "build=false" >> "$GITHUB_OUTPUT" @@ -121,13 +142,8 @@ jobs: strategy: fail-fast: false matrix: - variant: - - name: "AVX2" - suffix: "avx2" - cmake_flags: "-DENABLE_AVX2=ON" - - name: "No AVX2" - suffix: "noavx2" - cmake_flags: "-DENABLE_AVX2=OFF" + # AVX2 always, without AVX2 for master only: see the job `changes` + variant: ${{ fromJSON(needs.changes.outputs.variants) }} steps: - name: Checkout repository @@ -177,6 +193,7 @@ jobs: # the unit tests run at the end of the build and load lua51.dll (the Lua screens), but ref/luajit has only its import # library. LuaJIT of the same 2.0 line is built here and put on PATH for them; it doesn't go into the uploaded build - name: Build lua51.dll for the unit tests + if: matrix.variant.tests shell: cmd run: | for /f "usebackq delims=" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "VSDIR=%%i" @@ -298,13 +315,8 @@ jobs: strategy: fail-fast: false matrix: - variant: - - name: "AVX2" - suffix: "avx2" - cmake_flags: "-DENABLE_AVX2=ON" - - name: "No AVX2" - suffix: "noavx2" - cmake_flags: "-DENABLE_AVX2=OFF" + # AVX2 always, without AVX2 for master only: see the job `changes` + variant: ${{ fromJSON(needs.changes.outputs.variants) }} steps: - name: Checkout repository @@ -571,7 +583,7 @@ jobs: publish: name: Publish public download - needs: [windows, linux] + needs: [changes, windows, linux] if: github.event_name != 'pull_request' runs-on: ubuntu-24.04 permissions: @@ -589,6 +601,7 @@ jobs: path: dist/maszyna-windows-x64 - name: Download Windows build (no AVX2) + if: needs.changes.outputs.noavx2 == 'true' uses: actions/download-artifact@v4 with: name: maszyna-windows-x64-noavx2-${{ env.CONFIG_WIN }} @@ -601,6 +614,7 @@ jobs: path: dist/maszyna-linux-x64 - name: Download Linux build (no AVX2) + if: needs.changes.outputs.noavx2 == 'true' uses: actions/download-artifact@v4 with: name: maszyna-linux-x64-noavx2-${{ env.CONFIG_LINUX }} @@ -612,6 +626,7 @@ jobs: # the artifacts lose the executable bit for dir in maszyna-linux-x64 maszyna-linux-x64-noavx2; do + [ -d "$dir" ] || continue find "$dir" -type f -exec sh -c 'file -b "$1" | grep -q "^ELF" && chmod +x "$1"' _ {} \; if [ -d "$dir/linuxpython64/bin" ]; then chmod +x "$dir"/linuxpython64/bin/* @@ -619,9 +634,12 @@ jobs: done (cd maszyna-windows-x64 && zip -qr9 ../maszyna-windows-x64.zip .) - (cd maszyna-windows-x64-noavx2 && zip -qr9 ../maszyna-windows-x64-noavx2.zip .) tar -czf maszyna-linux-x64.tar.gz -C maszyna-linux-x64 . - tar -czf maszyna-linux-x64-noavx2.tar.gz -C maszyna-linux-x64-noavx2 . + # without AVX2: master only + if [ -d maszyna-windows-x64-noavx2 ]; then + (cd maszyna-windows-x64-noavx2 && zip -qr9 ../maszyna-windows-x64-noavx2.zip .) + tar -czf maszyna-linux-x64-noavx2.tar.gz -C maszyna-linux-x64-noavx2 . + fi ls -la - name: Publish rolling release of the branch @@ -636,23 +654,26 @@ jobs: tag="build-$slug" base="${{ github.server_url }}/${{ github.repository }}/releases/download/$tag" + assets=(dist/maszyna-windows-x64.zip dist/maszyna-linux-x64.tar.gz) + links=("- Windows: $base/maszyna-windows-x64.zip" "- Linux: $base/maszyna-linux-x64.tar.gz") + if [ -f dist/maszyna-windows-x64-noavx2.zip ]; then + assets+=(dist/maszyna-windows-x64-noavx2.zip dist/maszyna-linux-x64-noavx2.tar.gz) + links+=("- Windows, CPUs without AVX2 (older than Haswell, 2013): $base/maszyna-windows-x64-noavx2.zip" + "- Linux, CPUs without AVX2: $base/maszyna-linux-x64-noavx2.tar.gz") + else + links+=("- CPUs without AVX2 (older than Haswell, 2013): built for master only, see the release build-master") + fi notes="$(printf '%s\n' \ "Automatic build of branch \`$BRANCH\`, commit $SHA, replaced by every push to the branch." \ "" \ "Download without a GitHub account:" \ - "- Windows: $base/maszyna-windows-x64.zip" \ - "- Windows, CPUs without AVX2 (older than Haswell, 2013): $base/maszyna-windows-x64-noavx2.zip" \ - "- Linux: $base/maszyna-linux-x64.tar.gz" \ - "- Linux, CPUs without AVX2: $base/maszyna-linux-x64-noavx2.tar.gz" \ + "${links[@]}" \ "" \ "Unpack over a MaSzyna installation (the game data isn't included). Build log: $RUN_URL")" gh release delete "$tag" --yes --cleanup-tag || true gh release create "$tag" \ - dist/maszyna-windows-x64.zip \ - dist/maszyna-windows-x64-noavx2.zip \ - dist/maszyna-linux-x64.tar.gz \ - dist/maszyna-linux-x64-noavx2.tar.gz \ + "${assets[@]}" \ --target "$SHA" \ --prerelease \ --latest=false \ From 6b9558f588e035404eeb25cd34ae99599fb835cd Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 10:56:17 +0100 Subject: [PATCH 17/30] refactor(physics): the faults of the equipment are a named set the physics sets The faults the scenery or the network sets on a vehicle (TDynamicObject:: Damage() with the number of a message, held as EngDmgFlag and tested as its bits 1, 4) are EquipmentFault and EquipmentFaultSet, and what each does moves out of TDynamicObject into physics::Vehicle::SetEquipmentFaults(). The number of a message comes in through FromBits() and goes back out through Bits(), as it was. The faults of the control and of the camshaft still hold the start and the steps of the controller by delays moved out of reach by 100000001 and back, the very same arithmetic, now named and in one place. Tests of it are added (test_equipment_faults.cpp), as nothing reached it before. The setters of the parts that took a parameter named as one of their queries (Pressure, Voltage) take Value instead. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- input/messaging.cpp | 2 +- physics/components/airsupply.h | 4 +- physics/components/body.cpp | 44 ++++++++++++++++++++ physics/components/collisions.cpp | 2 +- physics/components/electrics.cpp | 4 +- physics/components/lowvoltage.h | 10 ++--- physics/components/pantographs.h | 10 ++--- physics/components/traction.cpp | 4 +- physics/vehicle.h | 4 +- physics/vehicletypes.h | 16 ++++++++ tests/unit/test_equipment_faults.cpp | 56 ++++++++++++++++++++++++++ vehicle/dynamic/update.cpp | 60 ++-------------------------- 12 files changed, 140 insertions(+), 76 deletions(-) create mode 100644 tests/unit/test_equipment_faults.cpp diff --git a/input/messaging.cpp b/input/messaging.cpp index 8e4b6829c..89a81faf5 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -188,7 +188,7 @@ OnCommandGet(multiplayer::DaneRozkaz const *pRozkaz) d->Damage( pRozkaz->cString[ 0 ] ); d = d->Prev(); // w drugą stronę też } - WyslijUszkodzenia( lookup->asName, static_cast(lookup->physics->EngDmgFlag) ); // zwrot informacji o pojeździe + WyslijUszkodzenia( lookup->asName, static_cast(lookup->physics->equipmentFaults.Bits()) ); // zwrot informacji o pojeździe } break; default: diff --git a/physics/components/airsupply.h b/physics/components/airsupply.h index 6a034f776..b5a04460b 100644 --- a/physics/components/airsupply.h +++ b/physics/components/airsupply.h @@ -33,7 +33,7 @@ class TrainPipe // the pressure in the pipe [bar], as it was last taken from its reservoir double const &Pressure() const { return pressure; } // the pressure taken from the reservoir of the pipe, after the flows of a step - void SetPressure(double const Pressure) { pressure = Pressure; } + void SetPressure(double const Value) { pressure = Value; } // the pipe stepped, its exchange of air through the hoses is yet to come (UpdatePipeCouplers()) bool CouplersPending() const { return couplersPending; } @@ -316,7 +316,7 @@ class AirSupply } // for the tests: the pressure in the reservoir as given, whatever its air - void SetPressureForTest(double const Pressure) { mainReservoirPressure = Pressure; } + void SetPressureForTest(double const Value) { mainReservoirPressure = Value; } private: double mainReservoirPressure{0.0}; diff --git a/physics/components/body.cpp b/physics/components/body.cpp index 084cf703d..dff55b0fe 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -1300,3 +1300,47 @@ namespace simulation weights_table Weights; } // namespace simulation + +void physics::Vehicle::SetEquipmentFaults(EquipmentFaultSet const Faults) +{ + if (Faults.HasAll(EquipmentFault::differentialRelay)) // różnicówka nie robi nic + { + MainSwitch(false); + FuseOff(); + } + // the faults of the control and of the camshaft hold the start, or the steps of the controller, by delays that never + // pass: the delays of the definition moved out of reach, and back when the fault clears + constexpr double faultoffset{100000001}; + constexpr double faultthreshold{100000000}; + if (Faults.HasAll(EquipmentFault::control)) // usterka sterowania + { + lineContactors.Open(); + if (InitialCtrlDelay < faultthreshold) + InitialCtrlDelay += faultoffset; + } + else if (InitialCtrlDelay > faultthreshold) + { + InitialCtrlDelay -= faultoffset; + } + if (Faults.HasAll(EquipmentFault::converter) && converter.config.start != start_t::disabled) // blokada przetwornicy + { + converter.Overload(); + } + air.compressor.SetFault(Faults.HasAll(EquipmentFault::compressor)); // blokada sprezarki + if (Faults.HasAll(EquipmentFault::camshaft)) // blokada wału + { + if (CtrlDelay < faultthreshold) + CtrlDelay += faultoffset; + if (CtrlDownDelay < faultthreshold) + CtrlDownDelay += faultoffset; + } + else + { + if (CtrlDelay > faultthreshold) + CtrlDelay -= faultoffset; + if (CtrlDownDelay > faultthreshold) + CtrlDownDelay -= faultoffset; + } + // hamowanie nagłe (emergencyBrake): nothing yet + equipmentFaults = Faults; +} diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index 8f985fe39..d8b34be61 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -782,7 +782,7 @@ void physics::Vehicle::rerail() void physics::Vehicle::repair_damage() { DamageFlag = {}; - EngDmgFlag = 0; + equipmentFaults = {}; WheelFlat = 0.0; brakes.alarmChain = false; // the crushed ends rebuilt diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index 49c64167a..0e75ef611 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -518,7 +518,7 @@ void physics::Vehicle::ConverterCheck(double const Timestep) supply.pantographPressureLock = pantographAir.IsPressureLockActive(); // HACK: allow carriages to operate converter without (missing) fuse prerequisite supply.highVoltage = Power > 1.0 ? MainCircuitPowered() : GetTrainsetHighVoltage() > 0.0; - supply.damaged = TestFlag(EngDmgFlag, 4); + supply.damaged = equipmentFaults.HasAll(EquipmentFault::converter); converter.Update(supply, Timestep); } @@ -869,7 +869,7 @@ bool physics::Vehicle::MainSwitchCheck() const (HasCamshaft ? IsMainCtrlActualNoPowerPos() : lineBreaker.config.closesOnlyAtNoPower ? IsMainCtrlNoPowerPos() : true) && - false == DamageFlag.HasAll(VehicleDamage::derailed) && false == TestFlag(EngDmgFlag, 1) && false == EmergencyBrakeHoldsMainOff(); + false == DamageFlag.HasAll(VehicleDamage::derailed) && false == equipmentFaults.HasAll(EquipmentFault::differentialRelay) && false == EmergencyBrakeHoldsMainOff(); } // ************************************************************************************************* diff --git a/physics/components/lowvoltage.h b/physics/components/lowvoltage.h index 0709d8101..a3c4b1332 100644 --- a/physics/components/lowvoltage.h +++ b/physics/components/lowvoltage.h @@ -33,10 +33,10 @@ class LowVoltageSupply Config config; // the battery of the definition (LMaxVoltage), charged - void SetBattery(double const Voltage) + void SetBattery(double const Value) { - batteryVoltage = Voltage; - config.nominalBatteryVoltage = static_cast(Voltage); + batteryVoltage = Value; + config.nominalBatteryVoltage = static_cast(Value); } bool IsBatteryOn() const { return batteryOn; } @@ -85,9 +85,9 @@ class LowVoltageSupply // the voltage of the battery circuit double Voltage24v() const { return power24vVoltage; } // the circuits in the step: the 24 V one from its voltage, the 110 V one as given - void SetSupply(double const Voltage24v, bool const Available110v) + void SetSupply(double const Volts24, bool const Available110v) { - power24vVoltage = Voltage24v; + power24vVoltage = Volts24; power24vAvailable = power24vVoltage > 0; power110vAvailable = Available110v; } diff --git a/physics/components/pantographs.h b/physics/components/pantographs.h index 4e406593a..be7ab5688 100644 --- a/physics/components/pantographs.h +++ b/physics/components/pantographs.h @@ -36,11 +36,11 @@ class PantographCircuit double Voltage(VehicleEnd const End) const { return End == VehicleEnd::front ? frontVoltage : rearVoltage; } double FrontVoltage() const { return frontVoltage; } double RearVoltage() const { return rearVoltage; } - void SetFrontVoltage(double const Voltage) { frontVoltage = Voltage; } - void SetRearVoltage(double const Voltage) { rearVoltage = Voltage; } + void SetFrontVoltage(double const Value) { frontVoltage = Value; } + void SetRearVoltage(double const Value) { rearVoltage = Value; } // the voltage supplied to the pantographs, from the overhead line the vehicle is under double SupplyVoltage() const { return supplyVoltage; } - void SetSupplyVoltage(double const Voltage) { supplyVoltage = Voltage; } + void SetSupplyVoltage(double const Value) { supplyVoltage = Value; } // the switch that lowers all of them bool AllDown() const { return allDown; } @@ -195,9 +195,9 @@ class PantographAir } // for the tests: the reservoirs at the given pressure, with the pressure switch primed or not - void SetForTest(double const Pressure, bool const PressureSwitchPrimed) + void SetForTest(double const Value, bool const PressureSwitchPrimed) { - pressure = Pressure; + pressure = Value; pressureSwitchActive = PressureSwitchPrimed; } diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index 3e2e8d468..137dd1446 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -1462,14 +1462,14 @@ bool physics::Vehicle::RelayReset(int const Relays, range_t const Notify) if (TestFlag(Relays, relay_t::maincircuitground) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && (protection.config.groundStart == start_t::manual || protection.config.groundStart == start_t::manualwithautofallback) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && - !TestFlag(EngDmgFlag, 1)) + false == equipmentFaults.HasAll(EquipmentFault::differentialRelay)) { // NOTE: true means the relay is operational reset |= protection.ResetGround(lowvoltagepower); } if (TestFlag(Relays, relay_t::tractionnmotoroverload) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && - !TestFlag(EngDmgFlag, 1)) + false == equipmentFaults.HasAll(EquipmentFault::differentialRelay)) { // NOTE: false means the relay is operational // TODO: cleanup, flip the FuseFlag code to match other relays diff --git a/physics/vehicle.h b/physics/vehicle.h index 4a1b9effa..5d49ab2a4 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -962,7 +962,7 @@ class Vehicle double ActFlowSpeed = 0.0; /*szybkosc stabilizatora*/ DamageSet DamageFlag; // the damage of the vehicle - int EngDmgFlag = 0; // kombinacja bitowa stalych usterek} + EquipmentFaultSet equipmentFaults; // the faults of the equipment set on the vehicle (SetEquipmentFaults()) // EndSignalsFlag: byte; {ABu 060205: zmiany - koncowki: 1/16 - swiatla prz/tyl, 2/31 - blachy prz/tyl} // HeadSignalsFlag: byte; {ABu 060205: zmiany - swiatla: 1/2/4 - przod, 16/32/63 - tyl} @@ -1646,6 +1646,8 @@ class Vehicle bool FuseOn(range_t const Notify = range_t::consist); // bezpiecznik nadamiary bool FuseFlagCheck(void) const; // sprawdzanie flagi nadmiarowego void FuseOff(void); // wylaczenie nadmiarowego + // the faults of the equipment the scenery or the network sets: each sets its fault, or clears it where it was set + void SetEquipmentFaults(EquipmentFaultSet Faults); bool UniversalResetButton(int const Button, range_t const Notify = range_t::consist); bool RelayReset(int const Relays, range_t const Notify = range_t::consist); // resets specified relays // the drive of the kind of engine of the vehicle (physics/components/drive.h) diff --git a/physics/vehicletypes.h b/physics/vehicletypes.h index 79ecd2ea5..dc83b6d88 100644 --- a/physics/vehicletypes.h +++ b/physics/vehicletypes.h @@ -92,6 +92,22 @@ template <> struct IsEnumSetKind : std::true_type }; using DamageSet = EnumSet; +// the faults of the equipment of a vehicle the scenery or the network sets (TDynamicObject::Damage()), in the numbers of +// the messages that carry them +enum class EquipmentFault : unsigned +{ + differentialRelay = 0x1, // the differential relay tripped: the line breaker opens and the fuse with it + control = 0x2, // the control: the line contactors open and the start doesn't go on + converter = 0x4, // the converter locked + compressor = 0x8, // the compressor locked + camshaft = 0x10, // the camshaft locked: the controller doesn't step + emergencyBrake = 0x20, // an emergency brake application, which does nothing more yet +}; +template <> struct IsEnumSetKind : std::true_type +{ +}; +using EquipmentFaultSet = EnumSet; + /// Reason for a derailment event. enum DerailReason { diff --git a/tests/unit/test_equipment_faults.cpp b/tests/unit/test_equipment_faults.cpp new file mode 100644 index 000000000..bd65cacb4 --- /dev/null +++ b/tests/unit/test_equipment_faults.cpp @@ -0,0 +1,56 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +// the faults of the equipment the scenery or the network sets on a vehicle (physics::Vehicle::SetEquipmentFaults(), +// TDynamicObject::Damage() with the number of a message) + +TEST_CASE("equipment faults: the number of a message comes back as it went in") { + auto const faults{EquipmentFaultSet::FromBits(0x2A)}; + CHECK(faults.HasAll(EquipmentFault::control)); + CHECK(faults.HasAll(EquipmentFault::compressor)); + CHECK(faults.HasAll(EquipmentFault::emergencyBrake)); + CHECK_FALSE(faults.HasAny(EquipmentFault::differentialRelay | EquipmentFault::converter | EquipmentFault::camshaft)); + CHECK(faults.Bits() == 0x2A); +} + +TEST_CASE("equipment faults: the fault of the control opens the line contactors and holds the start until it clears") { + test::vehicle loco{test::definition::fiz("4e_v1/4e")}; + auto const delay{loco->InitialCtrlDelay}; + loco->lineContactors.Close(); + loco->SetEquipmentFaults(EquipmentFault::control); + CHECK(loco->equipmentFaults.HasAll(EquipmentFault::control)); + CHECK_FALSE(loco->lineContactors.IsClosed()); + CHECK(loco->InitialCtrlDelay > 100000000.0); + // set again, it doesn't move the delay further + loco->SetEquipmentFaults(EquipmentFault::control); + CHECK(loco->InitialCtrlDelay < 200000000.0); + loco->SetEquipmentFaults({}); + CHECK(loco->equipmentFaults.Empty()); + CHECK(loco->InitialCtrlDelay == doctest::Approx(delay)); +} + +TEST_CASE("equipment faults: the fault of the compressor moves its pressures out of reach, and back") { + test::vehicle loco{test::definition::fiz("4e_v1/4e")}; + auto const minpressure{loco->air.compressor.config.minPressure}; + auto const maxpressure{loco->air.compressor.config.maxPressure}; + REQUIRE(minpressure > 0.0); + loco->SetEquipmentFaults(EquipmentFault::compressor); + CHECK(loco->air.compressor.config.minPressure < 0.0); + CHECK(loco->air.compressor.config.maxPressure < 0.0); + loco->SetEquipmentFaults({}); + CHECK(loco->air.compressor.config.minPressure == doctest::Approx(minpressure)); + CHECK(loco->air.compressor.config.maxPressure == doctest::Approx(maxpressure)); +} + +TEST_CASE("equipment faults: the fault of the camshaft holds the steps of the controller until it clears") { + test::vehicle loco{test::definition::fiz("4e_v1/4e")}; + auto const delay{loco->CtrlDelay}; + auto const downdelay{loco->CtrlDownDelay}; + loco->SetEquipmentFaults(EquipmentFault::camshaft); + CHECK(loco->CtrlDelay > 100000000.0); + CHECK(loco->CtrlDownDelay > 100000000.0); + loco->SetEquipmentFaults({}); + CHECK(loco->CtrlDelay == doctest::Approx(delay)); + CHECK(loco->CtrlDownDelay == doctest::Approx(downdelay)); +} diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index cb4d0f1a8..f80d991d6 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -1110,63 +1110,9 @@ void TDynamicObject::RadioStop() //--------------------------------------------------------------------------- void TDynamicObject::Damage(char flag) { - if (flag & 1) //różnicówka nie robi nic - { - physics->MainSwitch(false); - physics->FuseOff(); - } - else - { - } - - if (flag & 2) //usterka sterowania - { - physics->lineContactors.Open(); - if (physics->InitialCtrlDelay<100000000) - physics->InitialCtrlDelay += 100000001; - } - else - { - if (physics->InitialCtrlDelay>100000000) - physics->InitialCtrlDelay -= 100000001; - } - - if (flag & 4) //blokada przetwornicy - { - if( physics->converter.config.start != start_t::disabled ) { - physics->converter.Overload(); - } - } - else - { - } - - physics->air.compressor.SetFault((flag & 8) != 0); //blokada sprezarki - - if (flag & 16) //blokada wału - { - if (physics->CtrlDelay<100000000) - physics->CtrlDelay += 100000001; - if (physics->CtrlDownDelay<100000000) - physics->CtrlDownDelay += 100000001; - } - else - { - if (physics->CtrlDelay>100000000) - physics->CtrlDelay -= 100000001; - if (physics->CtrlDownDelay>100000000) - physics->CtrlDownDelay -= 100000001; - } - - if (flag & 32) //hamowanie nagŁe - { - } - else - { - } - - physics->EngDmgFlag = flag; -}; + // the number of the message, as a char (sign extended as the number was) + physics->SetEquipmentFaults(EquipmentFaultSet::FromBits(flag)); +} void TDynamicObject::OverheadTrack(float o) { // ewentualne wymuszanie jazdy From ea7a770d6cf95cddc99db88b8c061eb5a89d4fea Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 11:01:47 +0100 Subject: [PATCH 18/30] refactor(physics): the step of the doors belongs to the doors The step of the doors of a vehicle (their lock, the requests to open and to close from the passengers, from the cab and by themselves, the permits, the movement of the doors and their steps, the timers of the doors that close after a while) and the state of their closure signalling move from physics::Vehicle into physics::door_data (Update(), Closure()). The vehicle hands the doors what they need as plain values (door_data::StepInputs: its speed, whether the doors have their voltage, whether it is a multiple unit, whether passengers are getting in or out) and keeps only that. The doors can now be tested on their own, without a vehicle (test_door_component.cpp): opening and closing from the cab, no movement without the voltage, the lock over its speed, the doors closing by themselves unless the passengers are getting in. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- physics/components/devices.h | 24 +++ physics/components/doors.cpp | 252 +++++++++++++++-------------- physics/vehicle.h | 10 +- tests/unit/test_door_component.cpp | 91 +++++++++++ 4 files changed, 250 insertions(+), 127 deletions(-) create mode 100644 tests/unit/test_door_component.cpp diff --git a/physics/components/devices.h b/physics/components/devices.h index 4b225a27e..f032bd84a 100644 --- a/physics/components/devices.h +++ b/physics/components/devices.h @@ -198,6 +198,30 @@ struct door_data // ld outputs bool is_locked{false}; double doorLockSpeed = 10.0; // predkosc przy ktorej wyzwalana jest blokada drzwi + + // what the doors need to know of the vehicle in the step + struct StepInputs + { + double velocity{0.0}; // [km/h] + bool powered{false}; // the doors have the voltage they work on + bool multipleUnit{false}; // the steps fold only once the door has closed + bool exchangingLoad{false}; // the passengers get in or out: the doors that close after a while stay open + }; + // the step of the doors: the lock, the requests, the movement of the doors and their steps, the timers + // (physics/components/doors.cpp) + void Update(StepInputs const &Inputs, double Deltatime); + // the state of the door closure signalling (SOD) of the vehicle + door_closure_t Closure() const; + + private: + // the permit, the state and the requests of a door, and whether it and its step open or close + void UpdateRequests(basic_door &door, StepInputs const &Inputs, bool localopencontrol, bool remoteopencontrol, bool localclosecontrol, bool remoteclosecontrol); + bool OpenRequest(basic_door const &door, bool localopencontrol, bool remoteopencontrol) const; + bool CloseRequest(basic_door const &door, StepInputs const &Inputs, bool localclosecontrol, bool remoteclosecontrol) const; + bool StepFolding(basic_door const &door) const; + float OpenDuration(basic_door const &door, bool localopencontrol, bool remoteopencontrol) const; + void Move(basic_door &door, StepInputs const &Inputs, double Deltatime); + void UpdateTimers(StepInputs const &Inputs, double Deltatime); }; struct water_heater diff --git a/physics/components/doors.cpp b/physics/components/doors.cpp index e1afcdba1..994015968 100644 --- a/physics/components/doors.cpp +++ b/physics/components/doors.cpp @@ -341,27 +341,32 @@ bool physics::Vehicle::signal_departure(bool const State, range_t const Notify) // state of the door closure signalling (SOD) of this vehicle: open while a door isn't fully closed, released while // the closed doors can be opened (a permit given, or, for doors that need none, no lock engaged), locked otherwise. // doors the crew doesn't close (autonomous) aren't signalled, the same as for the door lights of the consist -door_closure_t physics::Vehicle::door_closure() const +door_closure_t physics::door_data::Closure() const { - if (Doors.range == 0.f || Doors.close_control == control_t::autonomous) + if (range == 0.f || close_control == control_t::autonomous) { return door_closure_t::none; } - if (std::ranges::any_of(Doors.instances, [](basic_door const &Door) { return false == Door.is_closed; })) + if (std::ranges::any_of(instances, [](basic_door const &Door) { return false == Door.is_closed; })) { return door_closure_t::open; } - if (Doors.is_locked) + if (is_locked) { return door_closure_t::locked; } - if (Doors.permit_needed && std::ranges::none_of(Doors.instances, [](basic_door const &Door) { return Door.open_permit; })) + if (permit_needed && std::ranges::none_of(instances, [](basic_door const &Door) { return Door.open_permit; })) { return door_closure_t::locked; } return door_closure_t::released; } +door_closure_t physics::Vehicle::door_closure() const +{ + return Doors.Closure(); +} + bool physics::Vehicle::door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const { return Doors.closure_signal ? door_closure_lamp(Consist, BlinkLit) : Doors.is_locked; @@ -383,98 +388,12 @@ bool door_closure_lamp(door_closure_t const State, bool const BlinkLit) // automatic door controller update void physics::Vehicle::update_doors(double const Deltatime) { - - if (Doors.range == 0.f) - { - return; - } // HACK: crude way to distinguish vehicles with actual doors - - // NBMX Obsluga drzwi, MC: zuniwersalnione - auto const localopencontrol{false == Doors.remote_only && (Doors.open_control == control_t::passenger || Doors.open_control == control_t::mixed)}; - auto const remoteopencontrol{Doors.open_control == control_t::driver || Doors.open_control == control_t::conductor || Doors.open_control == control_t::mixed}; - auto const localclosecontrol{false == Doors.remote_only && (Doors.close_control == control_t::passenger || Doors.close_control == control_t::mixed)}; - auto const remoteclosecontrol{Doors.close_control == control_t::driver || Doors.close_control == control_t::conductor || Doors.close_control == control_t::mixed}; - - Doors.is_locked = true == Doors.has_lock && true == Doors.lock_enabled && Vel >= Doors.doorLockSpeed; - - for (auto &door : Doors.instances) - { - update_door_requests(door, localopencontrol, remoteopencontrol, localclosecontrol, remoteclosecontrol); - move_door(door, Deltatime); - } - - if (false == Doors.instances[VehicleSide::right].is_open && false == Doors.instances[VehicleSide::left].is_open) - { - return; - } - - if (Doors.auto_duration > 0.f) - { - update_door_timers(Deltatime); - } - /* - // the door are closed if their timer goes below 0, or if the vehicle is moving faster than defined threshold - std::array const doorids { VehicleSide::right, VehicleSide::left }; - for( auto const doorid : doorids ) { - auto const &door { Doors.instances[ doorid ] }; - if( true == door.is_open ) { - if( ( ( Doors.auto_velocity != -1.f ) && ( Vel > Doors.auto_velocity ) ) - || ( ( door.auto_timer != -1.f ) && ( door.auto_timer <= 0.f ) ) ) { - // close the door and set the timer to expired state (closing may happen sooner if vehicle starts moving) - OperateDoors( doorid, false, range_t::local ); - } - } - } - */ -} - -// the permit, the state and the requests of a door, and whether it and its step open or close -void physics::Vehicle::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 physics::Vehicle::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 physics::Vehicle::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); + door_data::StepInputs inputs; + inputs.velocity = Vel; + inputs.powered = doors_powered(); + inputs.multipleUnit = is_multiple_unit(); + inputs.exchangingLoad = (LoadStatus & (2 | 1)) != 0; + Doors.Update(inputs, Deltatime); } // whether the doors have the voltage they work on @@ -491,44 +410,141 @@ bool physics::Vehicle::doors_powered() const return Doors.voltage == 110 && lowVoltage.Is110vAvailable(); } +// the step of the doors: the lock, the requests, the movement of the doors and their steps, the timers +void physics::door_data::Update(StepInputs const &Inputs, double const Deltatime) +{ + + if (range == 0.f) + { + return; + } // HACK: crude way to distinguish vehicles with actual doors + + // NBMX Obsluga drzwi, MC: zuniwersalnione + auto const localopencontrol{false == remote_only && (open_control == control_t::passenger || open_control == control_t::mixed)}; + auto const remoteopencontrol{open_control == control_t::driver || open_control == control_t::conductor || open_control == control_t::mixed}; + auto const localclosecontrol{false == remote_only && (close_control == control_t::passenger || close_control == control_t::mixed)}; + auto const remoteclosecontrol{close_control == control_t::driver || close_control == control_t::conductor || close_control == control_t::mixed}; + + is_locked = true == has_lock && true == lock_enabled && Inputs.velocity >= doorLockSpeed; + + for (auto &door : instances) + { + UpdateRequests(door, Inputs, localopencontrol, remoteopencontrol, localclosecontrol, remoteclosecontrol); + Move(door, Inputs, Deltatime); + } + + if (false == instances[VehicleSide::right].is_open && false == instances[VehicleSide::left].is_open) + { + return; + } + + if (auto_duration > 0.f) + { + UpdateTimers(Inputs, Deltatime); + } + /* + // the door are closed if their timer goes below 0, or if the vehicle is moving faster than defined threshold + std::array const doorids { VehicleSide::right, VehicleSide::left }; + for( auto const doorid : doorids ) { + auto const &door { instances[ doorid ] }; + if( true == door.is_open ) { + if( ( ( auto_velocity != -1.f ) && ( Inputs.velocity > auto_velocity ) ) + || ( ( door.auto_timer != -1.f ) && ( door.auto_timer <= 0.f ) ) ) { + // close the door and set the timer to expired state (closing may happen sooner if vehicle starts moving) + OperateDoors( doorid, false, range_t::local ); + } + } + } + */ +} + +// the permit, the state and the requests of a door, and whether it and its step open or close +void physics::door_data::UpdateRequests(basic_door &door, StepInputs const &Inputs, 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 == permit_presets.empty() // ...there's no preset switch controlling permit state... + || (false == 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 >= range && (false == step_enabled || door.step_position >= (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 == permit_needed || door.open_permit); + door.remote_open = (door.remote_open || remote_only) && false == door.is_open && (false == 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{OpenRequest(door, localopencontrol, remoteopencontrol)}; + auto const closerequest{CloseRequest(door, Inputs, localclosecontrol, remoteclosecontrol)}; + auto const ispowered{Inputs.powered}; + + door.is_opening = false == door.is_open && true == ispowered && false == closerequest && (true == door.is_opening || (true == openrequest && false == is_locked)); + door.is_closing = false == door.is_closed && true == ispowered && false == openrequest && (door.is_closing || closerequest); + door.step_unfolding = step_range != 0.f && step_enabled && false == is_locked && door.step_position < 1.f && door.is_opening; + door.step_folding = StepFolding(door); + + if (true == door.is_opening) + { + door.auto_timer = OpenDuration(door, localopencontrol, remoteopencontrol); + } +} + +// whether the door is asked to open, by the passengers, from afar or by itself +bool physics::door_data::OpenRequest(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const +{ + auto const autoopenrequest{open_control == control_t::autonomous && (false == 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 physics::door_data::CloseRequest(basic_door const &door, StepInputs const &Inputs, bool const localclosecontrol, bool const remoteclosecontrol) const +{ + auto const autocloserequest{(auto_velocity != -1.f && Inputs.velocity > auto_velocity) || (door.auto_timer != -1.f && door.auto_timer <= 0.f) || + (permit_needed && false == door.open_permit)}; + return (door.remote_close && remoteclosecontrol) || (door.local_close && localclosecontrol) || (autocloserequest && door.is_open); +} + // 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 physics::Vehicle::door_step_folding(basic_door const &door) const +bool physics::door_data::StepFolding(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); + auto const mayfold{false == step_enabled || (permit_needed ? false == door.open_permit : door.is_closing)}; + return unfolded && mayfold && (door.close_delay > 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 physics::Vehicle::door_open_duration(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const +float physics::door_data::OpenDuration(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const { if (localopencontrol && door.local_open) { - return Doors.auto_duration; + return auto_duration; } - if (remoteopencontrol && door.remote_open && Doors.auto_include_remote) + if (remoteopencontrol && door.remote_open && auto_include_remote) { - return Doors.auto_duration; + return auto_duration; } return -1.f; } // a door and its step moved as they open or close -void physics::Vehicle::move_door(basic_door &door, double const Deltatime) +void physics::door_data::Move(basic_door &door, StepInputs const &Inputs, 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) + || step_type == 2) { // no wait for rotating doorstep door.open_delay += static_cast(Deltatime); - if (door.open_delay > Doors.open_delay) + if (door.open_delay > open_delay) { - door.position = std::min(Doors.range, static_cast(door.position + Doors.open_rate * Deltatime)); + door.position = std::min(range, static_cast(door.position + open_rate * Deltatime)); } } door.close_delay = 0.f; @@ -537,9 +553,9 @@ void physics::Vehicle::move_door(basic_door &door, double const Deltatime) { // close door door.close_delay += static_cast(Deltatime); - if (door.close_delay > Doors.close_delay) + if (door.close_delay > close_delay) { - door.position = std::max(0.f, static_cast(door.position - Doors.close_rate * Deltatime)); + door.position = std::max(0.f, static_cast(door.position - close_rate * Deltatime)); } door.open_delay = 0.f; } @@ -547,31 +563,31 @@ void physics::Vehicle::move_door(basic_door &door, double const Deltatime) if (door.step_unfolding) { // unfold left doorstep - door.step_position = std::min(1.f, static_cast(door.step_position + Doors.step_rate * Deltatime)); + door.step_position = std::min(1.f, static_cast(door.step_position + step_rate * Deltatime)); } if (door.step_folding) { // fold left doorstep - if (is_multiple_unit()) + if (Inputs.multipleUnit) { // 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)); + door.step_position = std::max(0.f, static_cast(door.step_position - step_rate * Deltatime)); } } else { - door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); + door.step_position = std::max(0.f, static_cast(door.step_position - step_rate * Deltatime)); } } } // the timers of the open doors which close after a while, kept running while the load is exchanged -void physics::Vehicle::update_door_timers(double const Deltatime) +void physics::door_data::UpdateTimers(StepInputs const &Inputs, double const Deltatime) { // update door timers if the door close after defined time - for (auto &door : Doors.instances) + for (auto &door : instances) { if (false == door.is_open) @@ -584,9 +600,9 @@ void physics::Vehicle::update_door_timers(double const Deltatime) 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) + if (door.auto_timer != -1.f && Inputs.exchangingLoad) { - door.auto_timer = Doors.auto_duration; + door.auto_timer = auto_duration; } } } diff --git a/physics/vehicle.h b/physics/vehicle.h index 5d49ab2a4..ef6bd1557 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -1756,16 +1756,8 @@ class Vehicle // 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; + // whether the doors have the voltage they work on 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); diff --git a/tests/unit/test_door_component.cpp b/tests/unit/test_door_component.cpp new file mode 100644 index 000000000..7840d9010 --- /dev/null +++ b/tests/unit/test_door_component.cpp @@ -0,0 +1,91 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "physics/components/devices.h" + +// the doors of a vehicle as a part of their own (physics::door_data::Update()), stepped without a vehicle + +namespace { + +// a door one metre wide, opened and closed from the cab at a metre a second, without a step or a lock +physics::door_data cab_controlled_doors() { + physics::door_data doors; + doors.open_control = control_t::driver; + doors.close_control = control_t::driver; + doors.range = 1.f; + doors.open_rate = 1.f; + doors.close_rate = 1.f; + return doors; +} + +void run(physics::door_data &Doors, physics::door_data::StepInputs const &Inputs, double Seconds) { + for (auto time{0.0}; time < Seconds; time += 0.05) { + Doors.Update(Inputs, 0.05); + } +} + +physics::door_data::StepInputs standing_powered() { + physics::door_data::StepInputs inputs; + inputs.powered = true; + return inputs; +} + +} // namespace + +TEST_CASE("door component: a door opened from the cab opens at its rate, and closes when asked to") { + auto doors{cab_controlled_doors()}; + auto &door{doors.instances[VehicleSide::left]}; + door.remote_open = true; + run(doors, standing_powered(), 0.5); + CHECK(door.position > 0.f); + CHECK(door.position < 1.f); + CHECK_FALSE(door.is_closed); + run(doors, standing_powered(), 1.0); + CHECK(door.is_open); + CHECK(door.position == doctest::Approx(1.f)); + CHECK(doors.instances[VehicleSide::right].is_closed); + door.remote_close = true; + run(doors, standing_powered(), 1.5); + CHECK(door.is_closed); + CHECK(door.position == doctest::Approx(0.f)); +} + +TEST_CASE("door component: without the voltage it works on, a door doesn't move") { + auto doors{cab_controlled_doors()}; + auto &door{doors.instances[VehicleSide::left]}; + door.remote_open = true; + auto inputs{standing_powered()}; + inputs.powered = false; + run(doors, inputs, 2.0); + CHECK(door.is_closed); + CHECK(door.position == doctest::Approx(0.f)); +} + +TEST_CASE("door component: the lock holds the doors closed over its speed") { + auto doors{cab_controlled_doors()}; + doors.has_lock = true; + auto &door{doors.instances[VehicleSide::left]}; + door.remote_open = true; + auto inputs{standing_powered()}; + inputs.velocity = doors.doorLockSpeed + 5.0; + run(doors, inputs, 2.0); + CHECK(doors.is_locked); + CHECK(door.is_closed); + CHECK(doors.Closure() == door_closure_t::locked); +} + +TEST_CASE("door component: doors that close after a while close by themselves, unless the passengers are getting in") { + auto doors{cab_controlled_doors()}; + doors.auto_duration = 1.f; + doors.auto_include_remote = true; + auto &door{doors.instances[VehicleSide::left]}; + door.remote_open = true; + run(doors, standing_powered(), 1.5); + REQUIRE(door.is_open); + auto exchanging{standing_powered()}; + exchanging.exchangingLoad = true; + run(doors, exchanging, 3.0); + CHECK(door.is_open); + run(doors, standing_powered(), 3.0); + CHECK(door.is_closed); +} From 7387e36df54ebabe3c83ff5033100cf9cb7c3bb9 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 11:01:48 +0100 Subject: [PATCH 19/30] docs(agents): the components of the vehicle, what concerns a consist, and what the renderer reads AGENTS.md says how a part of physics::Vehicle is written (a public config from the .fiz, the state private behind queries and operations, its own logic fed with plain values, ...ForTest() for the tests), that what concerns a consist works on its vehicles given in order rather than on TDynamicObject, and that the renderer and the rest outside physics/ and vehicle/ read a vehicle through TDynamicObject. --- AGENTS.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 533d09efa..8b7f97f8d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -118,6 +118,18 @@ couplers, collisions, derailment) and `vehicle/` (the vehicle in the scenery, th - The commands between the vehicles are `VehicleCommand` (`physics/vehiclecommand.h`); their text names only matter where a command comes as text. - What depends on the kind of drive (`EngineType`) goes into its class in `physics/components/drive.*`, not into a new `switch`. +- The parts of `physics::Vehicle` are components, as `physics/components/maincircuit.h`, `lowvoltage.h`, `pantographs.h` and + `airsupply.h` show: what the `.fiz` defines is in their public `config`, written only by the parser and the setup of the vehicle; + their state is private, read through queries and changed through operations named after what happens (`Close()`, + `ResetGround()`, `Switch()`). The logic that concerns only a part is its own (`Update()` of the converter, of the compressor, of + the air of the pantographs), and the vehicle hands it what it needs as plain values (`ConverterSupply`, `CompressorInputs`) rather + than a `physics::Vehicle &`. The vehicle decides when a part acts and follows up what a step of it reports. A test that sets a + state directly uses the `...ForTest()` operation of the part, never a back door in the game's code. A new part follows the same + pattern, and a part being worked on moves to it. +- What concerns a consist rather than a vehicle works on the vehicles of the consist given to it in their order + (`physics::ConsistBrakeBlending`), not on `TDynamicObject`, so that it can be tested without the scenery. +- The renderer and the rest of the simulator outside `physics/` and `vehicle/` read a vehicle through `TDynamicObject` (its + dimensions, speed, active cab, lights), not through `physics/vehicle.h`. ## Renderers: the move to OpenGL 4.6 and Vulkan From 84f1aa251535978f9ccd31f4c88064ac7dbd1d79 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 12:26:21 +0100 Subject: [PATCH 20/30] refactor(physics): the controllers and the switches of the cab are private to the vehicle The positions of the master and the secondary controller, of the analog controller and of the lights selector, the occupied cab, the horns, the radio and its fuse, the radio-stop, the wipers' switch, the dimmer, the mirrors' button, the end-of-train signalling and the forced resistor fans: fourteen fields the cab, the AI, the scenery and the tests wrote straight into physics::Vehicle are private now. The rest of the simulator reads them through queries named as the fields were (MainCtrlPos(), Radio(), ...) and changes them through operations (SetMainCtrlPos(), SetRadio(), ...), so every place that moves a controller past its own stepping (IncMainCtrl()) is named and can be found; the compiler keeps anything else out. Inside the vehicle they keep their meaning under camelCase names. The queries return const references, as the gauges of the cab bind to them. The .fiz keys are untouched. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- application/consistviews.cpp | 4 +- application/driverhints.cpp | 32 ++-- application/drivermode.cpp | 26 +-- application/driveruipanels.cpp | 8 +- application/editormode.cpp | 2 +- audio/sound.cpp | 2 +- input/drivermouseinput.cpp | 8 +- input/messaging.cpp | 6 +- physics/components/body.cpp | 6 +- physics/components/cab.cpp | 16 +- physics/components/commands.cpp | 6 +- physics/components/controllers.cpp | 184 +++++++++---------- physics/components/diesel.cpp | 42 ++--- physics/components/drive.cpp | 20 +- physics/components/electrics.cpp | 2 +- physics/components/fizsections.cpp | 8 +- physics/components/pneumatics.cpp | 10 +- physics/components/securitysystem.cpp | 8 +- physics/components/setup.cpp | 2 +- physics/components/traction.cpp | 126 ++++++------- physics/consistbraking.cpp | 11 +- physics/vehicle.h | 72 +++++--- simulation/blackboxrecorder.cpp | 16 +- tests/unit/drive.cpp | 2 +- tests/unit/golden.cpp | 4 +- tests/unit/scenario.cpp | 2 +- tests/unit/test_6dg_power_steps.cpp | 6 +- tests/unit/test_cab.cpp | 8 +- tests/unit/test_camshaft.cpp | 4 +- tests/unit/test_cntrl.cpp | 42 ++--- tests/unit/test_commands.cpp | 6 +- tests/unit/test_consist_braking.cpp | 6 +- tests/unit/test_crew.cpp | 22 +-- tests/unit/test_definition.cpp | 2 +- tests/unit/test_diesel.cpp | 6 +- tests/unit/test_dimmer.cpp | 32 ++-- tests/unit/test_drivingaid.cpp | 16 +- tests/unit/test_dynamic_brake_diesel.cpp | 4 +- tests/unit/test_elf_controller.cpp | 46 ++--- tests/unit/test_engine_shutdown.cpp | 2 +- tests/unit/test_engine_start.cpp | 10 +- tests/unit/test_field_shunting.cpp | 12 +- tests/unit/test_gauge_scale.cpp | 10 +- tests/unit/test_handover.cpp | 22 +-- tests/unit/test_line_contactors.cpp | 2 +- tests/unit/test_mains_before_pantographs.cpp | 14 +- tests/unit/test_pressure_switch.cpp | 12 +- tests/unit/test_radio.cpp | 22 +-- tests/unit/test_speed_control.cpp | 44 ++--- tests/unit/test_traction.cpp | 6 +- tests/unit/test_uc_steps.cpp | 12 +- tests/unit/vehicle.cpp | 2 +- vehicle/Camera.cpp | 2 +- vehicle/ai/consist.cpp | 14 +- vehicle/ai/controls.cpp | 160 ++++++++-------- vehicle/ai/doors.cpp | 2 +- vehicle/ai/force.cpp | 4 +- vehicle/ai/obstacles.cpp | 2 +- vehicle/ai/orders.cpp | 4 +- vehicle/ai/physicslog.cpp | 4 +- vehicle/ai/situation.cpp | 26 +-- vehicle/cab/auxiliarycommands.cpp | 2 +- vehicle/cab/brakecommands.cpp | 12 +- vehicle/cab/cabcommands.cpp | 20 +- vehicle/cab/controllercommands.cpp | 16 +- vehicle/cab/doorcommands.cpp | 6 +- vehicle/cab/equipmentcommands.cpp | 12 +- vehicle/cab/lightcommands.cpp | 34 ++-- vehicle/cab/setup.cpp | 28 +-- vehicle/cab/signalcommands.cpp | 34 ++-- vehicle/cab/sounds.cpp | 2 +- vehicle/cab/train.cpp | 56 +++--- vehicle/cab/update.cpp | 52 +++--- vehicle/crew.cpp | 8 +- vehicle/crewchange.cpp | 4 +- vehicle/drivingaid.cpp | 4 +- vehicle/dynamic/animations.cpp | 4 +- vehicle/dynamic/lifecycle.cpp | 2 +- vehicle/dynamic/lights.cpp | 8 +- vehicle/dynamic/sounds.cpp | 8 +- vehicle/dynamic/update.cpp | 14 +- vehicle/dynamic/visual.cpp | 2 +- vehicle/enginestart.cpp | 2 +- vehicle/handover.cpp | 12 +- vehicle/mainctrlact.h | 4 +- widgets/vehicleparams.cpp | 6 +- world/TrkFoll.cpp | 2 +- 87 files changed, 798 insertions(+), 769 deletions(-) diff --git a/application/consistviews.cpp b/application/consistviews.cpp index 4d9fe76ab..55da9ca81 100644 --- a/application/consistviews.cpp +++ b/application/consistviews.cpp @@ -64,7 +64,7 @@ cameraviews::coupler coupler_of(TDynamicObject const *Vehicle, VehicleEnd const // 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->physics->CabOccupied < 0 ? -1 : 1}; + auto const cab{Driven->physics->CabOccupied() < 0 ? -1 : 1}; auto const direction{Driven->physics->DirActive < 0 ? -1 : 1}; return cab * direction; } @@ -235,7 +235,7 @@ cameraviews::placement consist_views::place_shunting(TCamera const &Camera, std: length += vehicle->physics->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->physics->CabOccupied)}; + auto const facing{cameraviews::driving_facing(m_vehicle->VectorFront(), Driven->VectorFront(), Driven->physics->CabOccupied())}; return cameraviews::topdown_placement(m_topdown, pose, facing); } diff --git a/application/driverhints.cpp b/application/driverhints.cpp index b3ba49897..fcc9b48dc 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -130,23 +130,23 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // radio case driver_hint::radioon: { if( AIControllFlag ) { - occupied->Radio = true; + occupied->SetRadio(true); } remove_hint( driver_hint::radiooff ); hint( Action, [this](float const /*Parameter*/) { - return occupied->Radio == true; } ); + return occupied->Radio() == true; } ); break; } case driver_hint::radiofuseon: { if( AIControllFlag ) { - occupied->RadioFuse = true; + occupied->SetRadioFuse(true); } hint( Action, [this](float const /*Parameter*/) { - return occupied->RadioFuse == true; } ); + return occupied->RadioFuse() == true; } ); break; } case driver_hint::radiochannel: { @@ -162,13 +162,13 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::radiooff: { if( AIControllFlag ) { - occupied->Radio = false; + occupied->SetRadio(false); } remove_hint( driver_hint::radioon ); hint( Action, [this](float const /*Parameter*/) { - return occupied->Radio == false; } ); + return occupied->Radio() == false; } ); break; } // oil pump @@ -507,7 +507,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // master controller case driver_hint::mastercontrollersetidle: { if( AIControllFlag ) { - while( mvControlling->RList[mvControlling->MainCtrlPos].Mn == 0 + while( mvControlling->RList[mvControlling->MainCtrlPos()].Mn == 0 && mvControlling->IncMainCtrl(1) ) { // all work is done in the loop header } @@ -516,16 +516,16 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this]( float const /*Parameter*/ ) { - return mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0; } ); + return mvControlling->RList[mvControlling->MainCtrlPos()].Mn > 0; } ); break; } case driver_hint::mastercontrollersetseriesmode: { - if (AIControllFlag && mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1) { + if (AIControllFlag && mvControlling->RList[ mvControlling->MainCtrlPos() ].Bn > 1) { // limit yourself to series mode - if( mvControlling->ScndCtrlPos ) { + if( mvControlling->ScndCtrlPos() ) { mvControlling->DecScndCtrl( 2 ); } - while( mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 + while( mvControlling->RList[mvControlling->MainCtrlPos()].Bn > 1 && mvControlling->DecMainCtrl(1) ) { // all work is performed in the header } @@ -534,7 +534,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this]( float const /*Parameter*/ ) { - return mvControlling->RList[mvControlling->MainCtrlPos].Bn < 2; } ); + return mvControlling->RList[mvControlling->MainCtrlPos()].Bn < 2; } ); break; } case driver_hint::mastercontrollersetzerospeed: { @@ -1007,19 +1007,19 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // horns case driver_hint::hornon: { if( AIControllFlag ) { - occupied->WarningSignal = static_cast( Actionparameter ); + occupied->SetWarningSignal(static_cast( Actionparameter )); } remove_hint( driver_hint::hornoff ); hint( Action, [this](float const /*Parameter*/) { // NOTE: we provide slightly larger horn activation window for human driver - return fWarningDuration + 5.0 < 0.05 || occupied->WarningSignal != 0; } ); + return fWarningDuration + 5.0 < 0.05 || occupied->WarningSignal() != 0; } ); break; } case driver_hint::hornoff: { if( AIControllFlag ) { - occupied->WarningSignal = 0; + occupied->SetWarningSignal(0); } /* // NOTE: for human driver the hint to switch horn on will disappear automatically @@ -1027,7 +1027,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) -> bool { - return ( occupied->WarningSignal == 0 ); } ); + return ( occupied->WarningSignal() == 0 ); } ); */ break; } diff --git a/application/drivermode.cpp b/application/drivermode.cpp index 3b132cb60..fcb1fe107 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -787,7 +787,7 @@ void driver_mode::update_camera(double const Deltatime) { // jeśli jazda w kabinie, przeliczyć trzeba parametry kamery /* - auto tempangle = controlled->VectorFront() * ( controlled->physics->CabOccupied == -1 ? -1 : 1 ); + auto tempangle = controlled->VectorFront() * ( controlled->physics->CabOccupied() == -1 ? -1 : 1 ); double modelrotate = atan2( -tempangle.x, tempangle.z ); */ if (false == FreeFlyModeFlag && true == Global.ctrlState && (m_input.keyboard.key(GLFW_KEY_LEFT) != GLFW_RELEASE || m_input.keyboard.key(GLFW_KEY_RIGHT) != GLFW_RELEASE)) @@ -799,7 +799,7 @@ void driver_mode::update_camera(double const Deltatime) // Camera.Yaw powinno być wyzerowane, aby po powrocie patrzeć do przodu Camera.Pos = controlled->GetPosition() + simulation::Train->MirrorPosition(lr); // pozycja lusterka // NOSONAR Camera.Angle.y = 0; // odchylenie na bok od Camera.LookAt - if (simulation::Train->Occupied()->CabOccupied == 0) + if (simulation::Train->Occupied()->CabOccupied() == 0) { // gdy w korytarzu Camera.LookAt = Camera.Pos - simulation::Train->GetDirection(); @@ -807,12 +807,12 @@ void driver_mode::update_camera(double const Deltatime) else if (Global.shiftState) { // patrzenie w bok przez szybę - Camera.LookAt = Camera.Pos - (lr ? -1.0 : 1.0) * controlled->VectorLeft() * (double)simulation::Train->Occupied()->CabOccupied; + Camera.LookAt = Camera.Pos - (lr ? -1.0 : 1.0) * controlled->VectorLeft() * (double)simulation::Train->Occupied()->CabOccupied(); } else { // patrzenie w kierunku osi pojazdu, z uwzględnieniem kabiny - jakby z lusterka, // ale bez odbicia - Camera.LookAt = Camera.Pos - simulation::Train->GetDirection() * (double)simulation::Train->Occupied()->CabOccupied; //-1 albo 1 + Camera.LookAt = Camera.Pos - simulation::Train->GetDirection() * (double)simulation::Train->Occupied()->CabOccupied(); //-1 albo 1 } auto const *dynamic{simulation::Train->Dynamic()}; auto const shakeangles{dynamic->shake_angles(dynamic->shake_between(shake_fraction()))}; @@ -867,7 +867,7 @@ void driver_mode::update_camera(double const Deltatime) Controlled->ABuSetModelShake( temp ); // ABu: koniec rzucania */ - if (simulation::Train->Occupied()->CabOccupied == 0) + if (simulation::Train->Occupied()->CabOccupied() == 0) { // gdy w korytarzu Camera.LookAt = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset) + Camera.m_owner->VectorFront() * 5.0; @@ -875,7 +875,7 @@ void driver_mode::update_camera(double const Deltatime) else { // patrzenie w kierunku osi pojazdu, z uwzględnieniem kabiny - Camera.LookAt = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset) + Camera.m_owner->VectorFront() * 5.0 * (double)simulation::Train->Occupied()->CabOccupied; //-1 albo 1 + Camera.LookAt = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset) + Camera.m_owner->VectorFront() * 5.0 * (double)simulation::Train->Occupied()->CabOccupied(); //-1 albo 1 } Camera.vUp = simulation::Train->GetUp(); } @@ -1192,7 +1192,7 @@ void driver_mode::DistantView(bool const Near) return; } - auto const cab = vehicle->physics->CabOccupied == 0 ? 1 : vehicle->physics->CabOccupied; + auto const cab = vehicle->physics->CabOccupied() == 0 ? 1 : vehicle->physics->CabOccupied(); auto const left = vehicle->VectorLeft() * (double)cab; if (true == Near) @@ -1203,7 +1203,7 @@ void driver_mode::DistantView(bool const Near) else { - Camera.Pos = vehicle->GetPosition() + vehicle->VectorFront() * (double)vehicle->physics->CabOccupied * 50.0 + glm::dvec3(-10.0 * left.x, 1.6, -10.0 * left.z); + Camera.Pos = vehicle->GetPosition() + vehicle->VectorFront() * (double)vehicle->physics->CabOccupied() * 50.0 + glm::dvec3(-10.0 * left.x, 1.6, -10.0 * left.z); } Camera.m_owner = nullptr; @@ -1256,7 +1256,7 @@ void driver_mode::ExternalView() else { // default view setup - auto const offsetflip{(vehicle->physics->CabOccupied == 0 ? 1 : vehicle->physics->CabOccupied) * + auto const offsetflip{(vehicle->physics->CabOccupied() == 0 ? 1 : vehicle->physics->CabOccupied()) * (vehicle->physics->DirActive == 0 ? 1 : vehicle->physics->DirActive)}; Camera.m_owneroffset = {1.5 * owner->physics->Dim.W * offsetflip, std::max(5.0, 1.25 * owner->physics->Dim.H), -0.4 * owner->physics->Dim.L * offsetflip}; @@ -1286,7 +1286,7 @@ void driver_mode::ExternalView() else { // default view setup - auto const offsetflip{(vehicle->physics->CabOccupied == 0 ? 1 : vehicle->physics->CabOccupied) * + auto const offsetflip{(vehicle->physics->CabOccupied() == 0 ? 1 : vehicle->physics->CabOccupied()) * (vehicle->physics->DirActive == 0 ? 1 : vehicle->physics->DirActive) * -1}; Camera.m_owneroffset = {1.5 * owner->physics->Dim.W * offsetflip, std::max(5.0, 1.25 * owner->physics->Dim.H), 0.2 * owner->physics->Dim.L * offsetflip}; @@ -1314,7 +1314,7 @@ void driver_mode::ExternalView() else { // default view setup - auto const offsetflip{(vehicle->physics->CabOccupied == 0 ? 1 : vehicle->physics->CabOccupied) * + auto const offsetflip{(vehicle->physics->CabOccupied() == 0 ? 1 : vehicle->physics->CabOccupied()) * (vehicle->physics->DirActive == 0 ? 1 : vehicle->physics->DirActive)}; Camera.m_owneroffset = {-0.65 * owner->physics->Dim.W * offsetflip, 0.90, 0.15 * owner->physics->Dim.L * offsetflip}; @@ -1382,14 +1382,14 @@ void driver_mode::CabView() Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl Camera.Angle.z = shakeangles.first; // hustanie kamery na boki - if (train->Occupied()->CabOccupied == 0) + if (train->Occupied()->CabOccupied() == 0) { Camera.LookAt = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset) + Camera.m_owner->VectorFront() * 5.0; } else { // patrz w strone wlasciwej kabiny - Camera.LookAt = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset) + Camera.m_owner->VectorFront() * 5.0 * (double)Camera.m_owner->physics->CabOccupied; + Camera.LookAt = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset) + Camera.m_owner->VectorFront() * 5.0 * (double)Camera.m_owner->physics->CabOccupied(); } train->pMechOffset = Camera.m_owneroffset; } diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 999217132..f667e43a3 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -862,7 +862,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.trainHeating.IsAllowed() ? 'h' : '.', physics.brakes.distributor->Releaser() ? '^' : '.', - std::string( m_input.mechanik ? STR(" R") + ( physics.Radio && physics.RadioFuse ? std::to_string( m_input.mechanik->iRadioChannel ) : "-" ) : "" ).c_str(), + std::string( m_input.mechanik ? STR(" R") + ( physics.Radio() && physics.RadioFuse() ? std::to_string( m_input.mechanik->iRadioChannel ) : "-" ) : "" ).c_str(), std::string( isdieselenginepowered ? STR(" oil pressure: ") + to_string( physics.OilPump.pressure, 2 ) : "" ).c_str(), // power transfers // 3000v @@ -888,9 +888,9 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Controllers:\n master: %d(%d), secondary: %s\nEngine output: %.1f, current: %.0f\nRevolutions:\n engine: %.0f, motors: %.0f\n engine fans: %.0f, motor fans: %.0f+%.0f, cooling fans: %.0f+%.0f"), // controllers - physics.MainCtrlPos, + physics.MainCtrlPos(), physics.MainCtrlActualPos, - std::string( isdieselinshuntmode ? to_string( physics.AnPos, 2 ) + STR(" (shunt mode)") : std::to_string( physics.ScndCtrlPos ) + "(" + std::to_string( physics.ScndCtrlActualPos ) + ")" ).c_str(), + std::string( isdieselinshuntmode ? to_string( physics.AnPos(), 2 ) + STR(" (shunt mode)") : std::to_string( physics.ScndCtrlPos() ) + "(" + std::to_string( physics.ScndCtrlActualPos ) + ")" ).c_str(), // engine physics.EnginePower, std::abs( physics.TrainType == train_type::emu ? physics.ShowCurrent( 0 ) : physics.Im ), @@ -962,7 +962,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Forces:\n tractive: %.1f, brake: %.1f, drag: %.2f%s\nAcceleration:\n tangential: %.2f, normal: %.2f (path radius: %s)\nVelocity: %.2f, distance traveled: %.2f\nPosition: [%.2f, %.2f, %.2f]"), // forces - physics.Ft * 0.001f * ( physics.CabOccupied ? physics.CabOccupied : vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabOccupied : 1 ) + 0.001f, + physics.Ft * 0.001f * ( physics.CabOccupied() ? physics.CabOccupied() : vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabOccupied() : 1 ) + 0.001f, physics.Fb * 0.001f, physics.FrictionForce() * 0.001f, physics.SlippingWheels ? " (!)" : "", diff --git a/application/editormode.cpp b/application/editormode.cpp index 1de1dda9b..7c9231d2b 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -7608,7 +7608,7 @@ void editor_mode::enter() auto const *vehicle = Camera.m_owner; if (vehicle) { - const int cab = vehicle->physics->CabOccupied == 0 ? 1 : vehicle->physics->CabOccupied; + const int cab = vehicle->physics->CabOccupied() == 0 ? 1 : vehicle->physics->CabOccupied(); const glm::dvec3 left = vehicle->VectorLeft() * (double)cab; Camera.Pos = glm::dvec3(Camera.Pos.x, vehicle->GetPosition().y, Camera.Pos.z) + left * vehicle->GetWidth() + glm::dvec3(1.25f * left.x, 1.6f, 1.25f * left.z); Camera.m_owner = nullptr; diff --git a/audio/sound.cpp b/audio/sound.cpp index a9a249ce5..020ea4601 100644 --- a/audio/sound.cpp +++ b/audio/sound.cpp @@ -978,7 +978,7 @@ sound_source::update_soundproofing() { listenervehicle ? 3 : // external view 4 ) : // free roam view - listenervehicle->physics->CabOccupied ) }; // some internal view so we can be sure listener isn't a nullptr + listenervehicle->physics->CabOccupied() ) }; // some internal view so we can be sure listener isn't a nullptr // location-based gain factor: std::uintptr_t soundproofingstamp = reinterpret_cast( listenervehicle ) diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index a2b3cc614..299dac67b 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -71,8 +71,8 @@ mouse_slider::bind( user_command const &Command ) { m_value = 0.5 + 0.5 * ( vehicle->CoupledCtrl ? - vehicle->MainCtrlPos + vehicle->ScndCtrlPos : - vehicle->MainCtrlPos ) / powerrange + vehicle->MainCtrlPos() + vehicle->ScndCtrlPos() : + vehicle->MainCtrlPos() ) / powerrange - 0.5 * occupied->brakes.independentPosition; m_analogue = true; m_invertrange = false; @@ -80,14 +80,14 @@ mouse_slider::bind( user_command const &Command ) { } case user_command::mastercontrollerset: { m_valuerange = vehicle->CoupledCtrl ? vehicle->MainCtrlPosNo + vehicle->ScndCtrlPosNo : vehicle->MainCtrlPosNo; - m_value = vehicle->CoupledCtrl ? vehicle->MainCtrlPos + vehicle->ScndCtrlPos : vehicle->MainCtrlPos; + m_value = vehicle->CoupledCtrl ? vehicle->MainCtrlPos() + vehicle->ScndCtrlPos() : vehicle->MainCtrlPos(); m_analogue = false; m_invertrange = false; break; } case user_command::secondcontrollerset: { m_valuerange = vehicle->ScndCtrlPosNo; - m_value = vehicle->ScndCtrlPos; + m_value = vehicle->ScndCtrlPos(); m_analogue = false; m_invertrange = true; break; diff --git a/input/messaging.cpp b/input/messaging.cpp index 89a81faf5..5d0489363 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -289,8 +289,8 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) r.fPar[14] = Vehicle->physics->brakes.cylinderPressure; // ciśnienie w CH r.fPar[15] = Vehicle->physics->air.MainReservoirPressure(); // ciśnienie w ZG r.fPar[16] = Vehicle->physics->Itot; // Prąd całkowity - r.iPar[17] = Vehicle->physics->MainCtrlPos; // Pozycja NJ - r.iPar[18] = Vehicle->physics->ScndCtrlPos; // Pozycja NB + r.iPar[17] = Vehicle->physics->MainCtrlPos(); // Pozycja NJ + r.iPar[18] = Vehicle->physics->ScndCtrlPos(); // Pozycja NB r.iPar[19] = Vehicle->physics->MainCtrlActualPos; // Pozycja jezdna r.iPar[20] = Vehicle->physics->ScndCtrlActualPos; // Pozycja bocznikowania r.iPar[21] = Vehicle->physics->ScndCtrlActualPos; // Pozycja bocznikowania @@ -328,7 +328,7 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) r.fPar[27 + p] = Vehicle->physics->ShowCurrent(p + 1); // amperomierze kolejnych grup // WriteLog("zapisalem prady"); - r.iPar[30] = Vehicle->physics->WarningSignal; // trabienie + r.iPar[30] = Vehicle->physics->WarningSignal(); // trabienie r.fPar[31] = Vehicle->physics->pantographCircuit.SupplyVoltage(); // napiecie WN // WriteLog("Parametry gotowe"); i <<= 2; // ilość bajtów diff --git a/physics/components/body.cpp b/physics/components/body.cpp index dff55b0fe..7a54d9e5b 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -67,7 +67,7 @@ int DirF(VehicleEnd CouplerN) // ************************************************************************************************* // główny konstruktor // ************************************************************************************************* -physics::Vehicle::Vehicle(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab) : TypeName(TypeNameInit), Name(NameInit), CabOccupied(Cab) +physics::Vehicle::Vehicle(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab) : TypeName(TypeNameInit), Name(NameInit), cabOccupied(Cab) { WriteLog("------------------------------------------------------"); WriteLog("init default physic values for " + NameInit + ", [" + TypeNameInit + "]"); @@ -421,14 +421,14 @@ void physics::Vehicle::compute_movement_(double const Deltatime) { if (MotorOverloadRelayHighThreshold) { // set high threshold - if (TrainType != train_type::et42 ? RList[MainCtrlPos].Bn < 2 : MainCtrlPos == 0) + if (TrainType != train_type::et42 ? RList[mainCtrlPos].Bn < 2 : mainCtrlPos == 0) { Imax = ImaxHi; } } else { // set low threshold - if (TrainType != train_type::et42 || MainCtrlPos == 0) + if (TrainType != train_type::et42 || mainCtrlPos == 0) { Imax = ImaxLo; } diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index ca4313e8a..2540af46f 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -51,9 +51,9 @@ bool physics::Vehicle::DirectionForward() bool physics::Vehicle::ChangeCab(int direction) { // zmiana kabiny i resetowanie ustawien - if (std::abs(CabOccupied + direction) < 2) + if (std::abs(cabOccupied + direction) < 2) { - CabOccupied = CabOccupied + direction; + cabOccupied = cabOccupied + direction; if (brakes.config.handlePositions > 0 && (brakes.config.kind == TBrakeSystem::Pneumatic || brakes.config.kind == TBrakeSystem::ElectroPneumatic)) { BrakeLevelSet(brakes.driverValve->GetPos(bh_NP)); @@ -62,8 +62,8 @@ bool physics::Vehicle::ChangeCab(int direction) } else BrakeLevelSet(brakes.driverValve->GetPos(bh_NP)); - MainCtrlPos = MainCtrlNoPowerPos(); - ScndCtrlPos = 0; + mainCtrlPos = MainCtrlNoPowerPos(); + scndCtrlPos = 0; return true; } return false; @@ -113,7 +113,7 @@ bool physics::Vehicle::CabActivisation(bool const Enforce) } if (OK) { - CabActive = CabOccupied; // sterowanie jest z kabiny z obsadą + CabActive = cabOccupied; // sterowanie jest z kabiny z obsadą DirAbsolute = DirActive * CabActive; CabMaster = true; SecuritySystem.set_enabled(true); // activate the alerter TODO: make it part of control based cab selection @@ -169,7 +169,7 @@ bool physics::Vehicle::CabDeactivisation(bool const Enforce) DepartureSignal = false; // nie buczeć z nieaktywnej kabiny SecuritySystem.set_enabled(false); // deactivate alerter TODO: make it part of control based cab selection - SendCtrlToNext(VehicleCommand::cabActivation, 0, CabOccupied); // CabActive==0! + SendCtrlToNext(VehicleCommand::cabActivation, 0, cabOccupied); // CabActive==0! } return OK; } @@ -220,7 +220,7 @@ bool physics::Vehicle::DirectionBackward(void) return false; } - if (DirActive == 1 && MainCtrlPos == 0 && TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor && MinCurrentSwitch(false)) + if (DirActive == 1 && mainCtrlPos == 0 && TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor && MinCurrentSwitch(false)) { return true; } @@ -245,6 +245,6 @@ bool physics::Vehicle::EIMDirectionChangeAllow(void) const // NOTE: disabled while eimic variables aren't immediately synced with master controller changes inside ai module OK = (EngineType != TEngineType::ElectricInductionMotor || ((eimic <= 0) && (eimic_real <= 0) && (Vel < 0.1))); */ - OK = MainCtrlPos <= MainCtrlMaxDirChangePos; + OK = mainCtrlPos <= MainCtrlMaxDirChangePos; return OK; } diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 68c3471e7..da3ffc58b 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -141,10 +141,10 @@ bool physics::Vehicle::RunControllerCommand(VehicleCommand const Command, double // sent as MainCtrlPosForCoupled(), passed on unchanged if (auto const position{MainCtrlPosFromCoupled(static_cast(floor(CValue1)))}; MainCtrlPosNo >= position) { - MainCtrlPos = position; + mainCtrlPos = position; if (DelayCtrlFlag) { - if (lineContactors.TimeSinceSwitch() >= InitialCtrlDelay && MainCtrlPos == 1) + if (lineContactors.TimeSinceSwitch() >= InitialCtrlDelay && mainCtrlPos == 1) lineContactors.RestartSwitchTimer(); } else if (lineContactors.TimeSinceSwitch() > CtrlDelay) @@ -156,7 +156,7 @@ bool physics::Vehicle::RunControllerCommand(VehicleCommand const Command, double { if (ScndCtrlPosNo >= floor(CValue1)) { - ScndCtrlPos = static_cast(floor(CValue1)); + scndCtrlPos = static_cast(floor(CValue1)); if (lineContactors.TimeSinceSwitch() > CtrlDelay) lineContactors.RestartSwitchTimer(); } diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index 7dbc286c8..778f05a25 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -48,7 +48,7 @@ bool physics::Vehicle::IncMainCtrl(int CtrlSpeed) // nie ma sterowania return false; } - if (TrainType == train_type::et22 && ScndCtrlPos != 0) + if (TrainType == train_type::et22 && scndCtrlPos != 0) { // w ET22 nie da się kręcić nastawnikiem przy włączonym boczniku return false; @@ -60,18 +60,18 @@ bool physics::Vehicle::IncMainCtrl(int CtrlSpeed) } bool OK = false; - if (MainCtrlPos < MainCtrlPosNo) + if (mainCtrlPos < MainCtrlPosNo) { OK = IncMainCtrlByEngine(CtrlSpeed); } else - { // MainCtrlPos>=MainCtrlPosNo + { // mainCtrlPos>=MainCtrlPosNo if (true == CoupledCtrl) { // wspólny wał nastawnika jazdy i bocznikowania - if (ScndCtrlPos < ScndCtrlPosNo) + if (scndCtrlPos < ScndCtrlPosNo) { // 3<3 -> false - ++ScndCtrlPos; + ++scndCtrlPos; OK = true; } else @@ -85,7 +85,7 @@ bool physics::Vehicle::IncMainCtrl(int CtrlSpeed) { ScndCtrlResistiveLockCheck(); // e.g. from the last series position on to the resistive parallel ones SendCtrlToNext(VehicleCommand::mainController, MainCtrlPosForCoupled(), CabActive); //??? - SendCtrlToNext(VehicleCommand::secondaryController, ScndCtrlPos, CabActive); + SendCtrlToNext(VehicleCommand::secondaryController, scndCtrlPos, CabActive); } // hunter-101012: poprawka @@ -97,7 +97,7 @@ bool physics::Vehicle::IncMainCtrl(int CtrlSpeed) { if (DelayCtrlFlag) { - if (lineContactors.TimeSinceSwitch() >= InitialCtrlDelay && MainCtrlPos == 1) + if (lineContactors.TimeSinceSwitch() >= InitialCtrlDelay && mainCtrlPos == 1) lineContactors.RestartSwitchTimer(); } else if (lineContactors.TimeSinceSwitch() > CtrlDelay) @@ -129,21 +129,21 @@ bool physics::Vehicle::IncMainCtrlSeriesMotor(int const CtrlSpeed) { 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)) + 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=train_type::et40) then // while Abs (Im)>IminHi do - // dec(MainCtrlPos); + // dec(mainCtrlPos); // OK:=false ; } else { // CtrlSpeed == 1 - ++MainCtrlPos; + ++mainCtrlPos; OK = true; - if (Imax == ImaxHi && RList[MainCtrlPos].Bn > 1) + if (Imax == ImaxHi && RList[mainCtrlPos].Bn > 1) { /* NOTE: disabled, relay configuration was moved to compute_movement_ if( true == MaxCurrentSwitch( false )) { @@ -153,7 +153,7 @@ bool physics::Vehicle::IncMainCtrlSeriesMotor(int const CtrlSpeed) */ if (TrainType == train_type::et42) { - --MainCtrlPos; + --mainCtrlPos; OK = false; } } @@ -161,15 +161,15 @@ bool physics::Vehicle::IncMainCtrlSeriesMotor(int const CtrlSpeed) // if (TrainType == "et40") // if (Abs(Im) > IminHi) // { - // MainCtrlPos--; //Blokada nastawnika po przekroczeniu minimalnego pradu + // mainCtrlPos--; //Blokada nastawnika po przekroczeniu minimalnego pradu // OK = false; // } //} } - if (TrainType == train_type::et42 && true == brakes.electrodynamic.on && MainCtrlPos > 20) + if (TrainType == train_type::et42 && true == brakes.electrodynamic.on && mainCtrlPos > 20) { - MainCtrlPos = 20; + mainCtrlPos = 20; OK = false; } return OK; @@ -195,13 +195,13 @@ bool physics::Vehicle::DecMainCtrl(int CtrlSpeed) else { // TBD, TODO: replace with mainctrlpowerpos() check? - if (MainCtrlPos > 0) + if (mainCtrlPos > 0) { - if (TrainType != train_type::et22 || ScndCtrlPos == 0) // Ra: ET22 blokuje nastawnik przy boczniku + if (TrainType != train_type::et22 || scndCtrlPos == 0) // Ra: ET22 blokuje nastawnik przy boczniku { - if (CoupledCtrl && ScndCtrlPos > 0) + if (CoupledCtrl && scndCtrlPos > 0) { - ScndCtrlPos--; // wspolny wal + scndCtrlPos--; // wspolny wal OK = true; } else @@ -217,7 +217,7 @@ bool physics::Vehicle::DecMainCtrl(int CtrlSpeed) { ScndCtrlResistiveLockCheck(); // the shunt drops when the master controller leaves a resistance-free position /*OK:=*/SendCtrlToNext(VehicleCommand::mainController, MainCtrlPosForCoupled(), CabActive); // hmmmm...???!!! - /*OK:=*/SendCtrlToNext(VehicleCommand::secondaryController, ScndCtrlPos, CabActive); + /*OK:=*/SendCtrlToNext(VehicleCommand::secondaryController, scndCtrlPos, CabActive); } } // if OK then LastRelayTime:=0; @@ -245,23 +245,23 @@ bool physics::Vehicle::DecMainCtrlByEngine(int const CtrlSpeed) bool physics::Vehicle::DecMainCtrlSeriesMotor(int const CtrlSpeed) { bool OK = false; - if (CtrlSpeed == 1) /*and (ScndCtrlPos=0)*/ + if (CtrlSpeed == 1) /*and (scndCtrlPos=0)*/ { - MainCtrlPos--; - // if (MainCtrlPos=0) and (ScndCtrlPos=0) and + mainCtrlPos--; + // if (mainCtrlPos=0) and (scndCtrlPos=0) and // (TrainType<>train_type::et40)and(TrainType<>train_type::ep05) then // StLinFlag:=false; - // if (MainCtrlPos=0) and (TrainType<>train_type::et40) and + // if (mainCtrlPos=0) and (TrainType<>train_type::et40) and // (TrainType<>train_type::ep05) then // MainCtrlActualPos:=0; //yBARC: co to tutaj robi? ;) OK = true; } - else if (CtrlSpeed > 1) /*and (ScndCtrlPos=0)*/ + else if (CtrlSpeed > 1) /*and (scndCtrlPos=0)*/ { OK = true; - if (RList[MainCtrlPos].R == 0) // Q: tu zrobilem = ;] + if (RList[mainCtrlPos].R == 0) // Q: tu zrobilem = ;] DecMainCtrl(1); - while (RList[MainCtrlPos].R > 0 && DecMainCtrl(1)) + while (RList[mainCtrlPos].R > 0 && DecMainCtrl(1)) ; // takie chamskie, potem poprawie} } return OK; @@ -276,13 +276,13 @@ bool physics::Vehicle::IsMainCtrlActualNoPowerPos() const bool physics::Vehicle::IsMainCtrlNoPowerPos() const { // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems - return MainCtrlPos <= MainCtrlNoPowerPos(); + return mainCtrlPos <= MainCtrlNoPowerPos(); } bool physics::Vehicle::IsMainCtrlMaxPowerPos() const { // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems - return MainCtrlPos == MainCtrlPosNo; + return mainCtrlPos == MainCtrlPosNo; } int physics::Vehicle::MainCtrlNoPowerPos() const @@ -318,7 +318,7 @@ int physics::Vehicle::MainCtrlActualPowerPos() const int physics::Vehicle::MainCtrlPowerPos() const { - return MainCtrlPos - MainCtrlNoPowerPos(); + return mainCtrlPos - MainCtrlNoPowerPos(); } int physics::Vehicle::EIMCtrlEmergencyPositions() const @@ -328,13 +328,13 @@ int physics::Vehicle::EIMCtrlEmergencyPositions() const bool physics::Vehicle::IsMainCtrlEmergencyPos() const { - return MainCtrlPos < EIMCtrlEmergencyPositions(); + return mainCtrlPos < EIMCtrlEmergencyPositions(); } int physics::Vehicle::MainCtrlPosForCoupled() const { // the emergency brake itself reaches the train through the brake pipe, vented by the vehicle driven from - return std::max(0, MainCtrlPos - EIMCtrlEmergencyPositions()); + return std::max(0, mainCtrlPos - EIMCtrlEmergencyPositions()); } int physics::Vehicle::MainCtrlPosFromCoupled(int const Position) const @@ -350,15 +350,15 @@ bool physics::Vehicle::IncScndCtrl(int CtrlSpeed) { bool OK = false; - if (brakes.electrodynamic.on && TrainType == train_type::et42 && CabActive != 0 && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0) + if (brakes.electrodynamic.on && TrainType == train_type::et42 && CabActive != 0 && IsMainCtrlNoPowerPos() && scndCtrlPos == 0) { OK = DynamicBrakeSwitch(false); } else if (ScndCtrlPosNo > 0 && CabActive != 0 && !(TrainType == train_type::et42 && (Imax == ImaxHi || (brakes.electrodynamic.on && MainCtrlPowerPos() > 0)))) { - // if (RList[MainCtrlPos].R=0) and (MainCtrlPos>0) and (ScndCtrlPos0) and (scndCtrlPos 1) { - ScndCtrlPos = ScndCtrlPosNo; // takie chamskie, potem poprawie + scndCtrlPos = ScndCtrlPosNo; // takie chamskie, potem poprawie } OK = true; } @@ -385,7 +385,7 @@ bool physics::Vehicle::IncScndCtrl(int CtrlSpeed) if (OK) { /*OK:=*/SendCtrlToNext(VehicleCommand::mainController, MainCtrlPosForCoupled(), CabActive); //??? - /*OK:=*/SendCtrlToNext(VehicleCommand::secondaryController, ScndCtrlPos, CabActive); + /*OK:=*/SendCtrlToNext(VehicleCommand::secondaryController, scndCtrlPos, CabActive); } } else // nie ma sterowania @@ -395,17 +395,17 @@ bool physics::Vehicle::IncScndCtrl(int CtrlSpeed) if (OK && lineContactors.TimeSinceSwitch() > CtrlDelay) lineContactors.RestartSwitchTimer(); - if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1 && MainCtrlPos > 0) + if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1 && mainCtrlPos > 0) { SpeedCtrlValue = Vel; if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1) { - MainCtrlActualPos = MainCtrlPos; + MainCtrlActualPos = mainCtrlPos; } SpeedCtrlUnit.IsActive = true; } - if (OK && SpeedCtrl && ScndCtrlPos == 1 && EngineType == TEngineType::DieselEngine) + if (OK && SpeedCtrl && scndCtrlPos == 1 && EngineType == TEngineType::DieselEngine) { // NOTE: round() already adds 0.5, are the ones added here as well correct? SpeedCtrlValue = static_cast(Round(Vel)); @@ -423,22 +423,22 @@ bool physics::Vehicle::DecScndCtrl(int CtrlSpeed) { bool OK = false; - if (IsMainCtrlNoPowerPos() && CabActive != 0 && TrainType == train_type::et42 && ScndCtrlPos == 0 && !brakes.electrodynamic.on && CtrlSpeed == 1) + if (IsMainCtrlNoPowerPos() && CabActive != 0 && TrainType == train_type::et42 && scndCtrlPos == 0 && !brakes.electrodynamic.on && CtrlSpeed == 1) { - // Ra: AI wywołuje z CtrlSpeed=2 albo gdy ScndCtrlPos>0 + // Ra: AI wywołuje z CtrlSpeed=2 albo gdy scndCtrlPos>0 OK = DynamicBrakeSwitch(true); } else if (ScndCtrlPosNo > 0 && CabActive != 0) { - if (ScndCtrlPos > 0 && !CoupledCtrl && (EngineType != TEngineType::DieselElectric || !AutoRelayFlag) && !IsScndCtrlLockedByMainCtrl()) + if (scndCtrlPos > 0 && !CoupledCtrl && (EngineType != TEngineType::DieselElectric || !AutoRelayFlag) && !IsScndCtrlLockedByMainCtrl()) { if (CtrlSpeed == 1) { - ScndCtrlPos--; + scndCtrlPos--; } else if (CtrlSpeed > 1) { - ScndCtrlPos = 0; // takie chamskie, potem poprawie + scndCtrlPos = 0; // takie chamskie, potem poprawie } OK = true; } @@ -447,7 +447,7 @@ bool physics::Vehicle::DecScndCtrl(int CtrlSpeed) if (OK) { /*OK:=*/SendCtrlToNext(VehicleCommand::mainController, MainCtrlPosForCoupled(), CabActive); //??? - /*OK:=*/SendCtrlToNext(VehicleCommand::secondaryController, ScndCtrlPos, CabActive); + /*OK:=*/SendCtrlToNext(VehicleCommand::secondaryController, scndCtrlPos, CabActive); } } else @@ -467,7 +467,7 @@ bool physics::Vehicle::DecScndCtrl(int CtrlSpeed) } } - if (OK && SpeedCtrl && ScndCtrlPos == 0 && EngineType == TEngineType::DieselEngine) + if (OK && SpeedCtrl && scndCtrlPos == 0 && EngineType == TEngineType::DieselEngine) { SpeedCtrlValue = 0; SpeedCtrlUnit.IsActive = false; @@ -483,36 +483,36 @@ bool physics::Vehicle::DecScndCtrl(int CtrlSpeed) bool physics::Vehicle::IsScndCtrlLockedByMainCtrl() const { // ET21, ET22, EP09: the field shunting engages only on the resistance-free positions of the master controller (eu07/maszyna#402) - return ScndCtrlResistiveLock && (IsMainCtrlNoPowerPos() || RList[MainCtrlPos].R >= 0.01); + return ScndCtrlResistiveLock && (IsMainCtrlNoPowerPos() || RList[mainCtrlPos].R >= 0.01); } void physics::Vehicle::ScndCtrlResistiveLockCheck() { // the shunt controller, locked in both directions on zero and the resistive positions, would otherwise stay engaged there once the // master controller is taken back (or set from elsewhere, e.g. by the AI or another vehicle of the consist) with the shunt on - if (ScndCtrlPos > 0 && !CoupledCtrl && IsScndCtrlLockedByMainCtrl()) + if (scndCtrlPos > 0 && !CoupledCtrl && IsScndCtrlLockedByMainCtrl()) { - ScndCtrlPos = 0; + scndCtrlPos = 0; } } int physics::Vehicle::GetVirtualScndPos() const { - if (TrainType == train_type::et42 && brakes.electrodynamic.on && !ScndCtrlPos) + if (TrainType == train_type::et42 && brakes.electrodynamic.on && !scndCtrlPos) return -1; - return ScndCtrlPos; + return scndCtrlPos; } bool physics::Vehicle::IsScndCtrlNoPowerPos() const { // TODO: refine the check on account of potential electric series vehicles with speed control - return ScndCtrlPos == 0 || true == SpeedCtrl; + return scndCtrlPos == 0 || true == SpeedCtrl; } bool physics::Vehicle::IsScndCtrlMaxPowerPos() const { // TODO: refine the check on account of potential electric series vehicles with speed control - return ScndCtrlPos == ScndCtrlPosNo || true == SpeedCtrl; + return scndCtrlPos == ScndCtrlPosNo || true == SpeedCtrl; } // ************************************************************************************************* @@ -561,7 +561,7 @@ bool physics::Vehicle::AutoRelayCheck(void) // sprawdzenie wszystkich warunkow (AutoRelayFlag, AutoSwitch, Im 0 || ScndCtrlPos > 0) && (!CoupledCtrl || RList[MainCtrlActualPos].Relay == MainCtrlPos)) + if (RList[MainCtrlActualPos].R == 0 && (ScndCtrlActualPos > 0 || scndCtrlPos > 0) && (!CoupledCtrl || RList[MainCtrlActualPos].Relay == mainCtrlPos)) { // zmieniaj scndctrlactualpos OK = AutoRelayShuntStep(ARFASI2); } @@ -596,7 +596,7 @@ bool physics::Vehicle::AutoRelayShuntStep(bool const ARFASI2) { bool OK = false; // scnd bez samoczynnego rozruchu - if (ScndCtrlActualPos < ScndCtrlPos) + if (ScndCtrlActualPos < scndCtrlPos) { if (lineContactors.TimeSinceSwitch() > CtrlDelay && ARFASI2) { @@ -605,7 +605,7 @@ bool physics::Vehicle::AutoRelayShuntStep(bool const ARFASI2) OK = true; } } - else if (ScndCtrlActualPos > ScndCtrlPos) + else if (ScndCtrlActualPos > scndCtrlPos) { if (lineContactors.TimeSinceSwitch() > CtrlDownDelay && TrainType != train_type::emu) { @@ -629,12 +629,12 @@ bool physics::Vehicle::AutoRelayMainStep(bool const ARFASI) auto const backwardslimit{DirActive < 0 && TrainType != train_type::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) || + && (RList[MainCtrlActualPos].Relay < mainCtrlPos || (RList[MainCtrlActualPos + 1].Relay == mainCtrlPos && MainCtrlActualPos < RlistSize) || (TrainType == train_type::et22 && DelayCtrlFlag))) { OK = AutoRelayMainUp(ARFASI); } - else if (RList[MainCtrlActualPos].Relay > MainCtrlPos) + else if (RList[MainCtrlActualPos].Relay > mainCtrlPos) { OK = AutoRelayMainDown(); } @@ -663,12 +663,12 @@ bool physics::Vehicle::AutoRelayMainUp(bool const ARFASI) return false; } - if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && MainCtrlPos != MainCtrlPosNo && FastSerialCircuit == 1) + if (RList[mainCtrlPos].R == 0 && mainCtrlPos > 0 && mainCtrlPos != MainCtrlPosNo && FastSerialCircuit == 1) { // szybkie wchodzenie na bezoporowa (303E) - // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: + // MainCtrlActualPos:=mainCtrlPos; //hunter-111012: ++MainCtrlActualPos; - if (MainCtrlPos - MainCtrlActualPos == 1) + 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 @@ -695,7 +695,7 @@ bool physics::Vehicle::AutoRelayMainNotchUp() bool OK = false; // WriteLog("LRT = " + FloatToStr(LastRelayTime) + ", " + // FloatToStr(CtrlDelay)); - if (TrainType == train_type::et22 && MainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || DelayCtrlFlag)) + if (TrainType == train_type::et22 && mainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || DelayCtrlFlag)) { // et22 z walem grupowym if (!DelayCtrlFlag) // najpierw przejscie @@ -742,10 +742,10 @@ bool physics::Vehicle::AutoRelayMainNotchUp() bool physics::Vehicle::AutoRelayMainDown() { bool OK = false; - if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && !(MainCtrlPos == MainCtrlPosNo) && FastSerialCircuit == 1) + if (RList[mainCtrlPos].R == 0 && mainCtrlPos > 0 && !(mainCtrlPos == MainCtrlPosNo) && FastSerialCircuit == 1) { // szybkie wchodzenie na bezoporowa (303E) - // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: + // MainCtrlActualPos:=mainCtrlPos; //hunter-111012: --MainCtrlActualPos; OK = true; if (RList[MainCtrlActualPos].R == 0) @@ -1036,7 +1036,7 @@ void physics::Vehicle::CheckEIMIC(double dt) // the controller (EIMCtrlType 0): the position of the main controller, or the analog one, or the brake asked void physics::Vehicle::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; + eimic = brakeDemand > 0.01 ? -brakeDemand : eimic_analog > 0.01 ? eimic_analog : (double)mainCtrlPos / (double)MainCtrlPosNo; if (EIMCtrlAdditionalZeros || EIMCtrlEmergency) { if (eimic > 0.001) @@ -1051,7 +1051,7 @@ void physics::Vehicle::EIMICFromController(double const brakeDemand, double cons // EIMCtrlType 1: the positions B+ to TMax move the value at a steady pace void physics::Vehicle::EIMICFromSteps(double dt) { - switch (MainCtrlPos) + switch (mainCtrlPos) { case 0: // B+ eimic -= std::clamp(1.0 + eimic, 0.0, dt * 0.14); // odejmuj do -1 @@ -1077,9 +1077,9 @@ void physics::Vehicle::EIMICFromSteps(double dt) default: break; } - if (MainCtrlPos >= 3 && eimic < 0) + if (mainCtrlPos >= 3 && eimic < 0) eimic = 0; - if (MainCtrlPos <= 3 && eimic > 0) + if (mainCtrlPos <= 3 && eimic > 0) eimic = 0; } @@ -1092,11 +1092,11 @@ void physics::Vehicle::EIMICFromFourPositions(double dt) // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() eimic = -1.0; } - else if (MainCtrlActualPos != MainCtrlPos || lineContactors.TimeSinceSwitch() > InitialCtrlDelay) + else if (MainCtrlActualPos != mainCtrlPos || lineContactors.TimeSinceSwitch() > InitialCtrlDelay) { - double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; + double delta = MainCtrlActualPos == mainCtrlPos ? dt * CtrlDelay : 0.01; // the positions below are those of the controller without the emergency brake position - switch (MainCtrlPos - EIMCtrlEmergencyPositions()) + switch (mainCtrlPos - EIMCtrlEmergencyPositions()) { case 0: case 1: @@ -1119,12 +1119,12 @@ void physics::Vehicle::EIMICFromFourPositions(double dt) break; } } - if (MainCtrlActualPos == MainCtrlPos) + if (MainCtrlActualPos == mainCtrlPos) lineContactors.AdvanceSwitchTimer(dt); else { lineContactors.RestartSwitchTimer(); - MainCtrlActualPos = MainCtrlPos; + MainCtrlActualPos = mainCtrlPos; } } @@ -1136,23 +1136,23 @@ void physics::Vehicle::EIMICFromUniversalController(double dt, double const brak UniversalControllerTrainBrake(); } - if (MainCtrlActualPos != MainCtrlPos || lineContactors.TimeSinceSwitch() > InitialCtrlDelay) + if (MainCtrlActualPos != mainCtrlPos || lineContactors.TimeSinceSwitch() > InitialCtrlDelay) { - auto const &position{UniCtrlList[MainCtrlPos]}; + 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 + 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 + 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; + eimic = UniCtrlValStep > 0.0 ? stepped_uc_value(eimic, ramped, position, UniCtrlValStep, MainCtrlActualPos != mainCtrlPos, eimic_step_progress) : ramped; } - if (MainCtrlActualPos == MainCtrlPos) + if (MainCtrlActualPos == mainCtrlPos) lineContactors.AdvanceSwitchTimer(dt); else { lineContactors.RestartSwitchTimer(); - MainCtrlActualPos = MainCtrlPos; + MainCtrlActualPos = mainCtrlPos; } if (brakes.distributor->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake eimic = 0; // shut off retarder @@ -1168,7 +1168,7 @@ void physics::Vehicle::EIMICFromUniversalController(double dt, double const brak // controller, at a brake handle moved alone, to the nearest position of the handle's void physics::Vehicle::UniversalControllerTrainBrake() { - if (UniCtrlList[MainCtrlPos].mode != brakes.handlePosition && MainCtrlActualPos == MainCtrlPos) // there was no move of controller, but brake only + if (UniCtrlList[mainCtrlPos].mode != brakes.handlePosition && MainCtrlActualPos == mainCtrlPos) // there was no move of controller, but brake only { if (brakes.handlePosition < UniCtrlList[MainCtrlPosNo].mode) BrakeLevelSet(UniCtrlList[MainCtrlPosNo].mode); // bottom clamping @@ -1176,14 +1176,14 @@ void physics::Vehicle::UniversalControllerTrainBrake() BrakeLevelSet(UniCtrlList[0].mode); // top clamping if (IsCabMaster()) { - while (brakes.handlePosition > UniCtrlList[MainCtrlPos].mode) + while (brakes.handlePosition > UniCtrlList[mainCtrlPos].mode) DecMainCtrl(1); // find nearest position - while (brakes.handlePosition < UniCtrlList[MainCtrlPos].mode) + while (brakes.handlePosition < UniCtrlList[mainCtrlPos].mode) IncMainCtrl(1); // find nearest position } } else // controller was moved - BrakeLevelSet(UniCtrlList[MainCtrlPos].mode); + BrakeLevelSet(UniCtrlList[mainCtrlPos].mode); } // the local brake of the TRAXX locomotives, by time: released, held or applied, which cuts the drive off @@ -1245,17 +1245,17 @@ void physics::Vehicle::CheckSpeedCtrl(double dt) double accfactor = SpeedCtrlUnit.DesiredPower; if (EIMCtrlType >= 2) { - if (MainCtrlPos < MainCtrlPosNo - 2) + if (mainCtrlPos < MainCtrlPosNo - 2) { SpeedCtrlUnit.Standby = true; } - if (MainCtrlPos > MainCtrlPosNo - 1) + if (mainCtrlPos > MainCtrlPosNo - 1) { SpeedCtrlUnit.Standby = false; } if (!SpeedCtrlUnit.BrakeIntervention && (brakes.distributor->GetEDBCP() > 0.4 || brakePipe.Pressure() < brakes.config.pipeHighPressure - 0.2)) SpeedCtrlUnit.Standby = true; - if (EIMCtrlType >= 3 && UniCtrlList[MainCtrlPos].SpeedUp <= 0) + if (EIMCtrlType >= 3 && UniCtrlList[mainCtrlPos].SpeedUp <= 0) { accfactor = 0.0; eimicSpeedCtrl = 0; @@ -1332,7 +1332,7 @@ void physics::Vehicle::SpeedCtrlRegulator(double dt, double const accfactor) { eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); } - if (Vel < SpeedCtrlUnit.StartVelocity && MainCtrlPos < MainCtrlPosNo) + if (Vel < SpeedCtrlUnit.StartVelocity && mainCtrlPos < MainCtrlPosNo) { eimicSpeedCtrl = 0; eimic = 0; @@ -1347,7 +1347,7 @@ bool physics::Vehicle::IsSpeedCtrlSeparate() const bool physics::Vehicle::IsSpeedCtrlEngaged() const { - return IsSpeedCtrlSeparate() ? SpeedCtrlUnit.IsActive : ScndCtrlPos > 0; + return IsSpeedCtrlSeparate() ? SpeedCtrlUnit.IsActive : scndCtrlPos > 0; } bool physics::Vehicle::SpeedCtrlSwitch(bool const State) diff --git a/physics/components/diesel.cpp b/physics/components/diesel.cpp index 489892607..b6c781690 100644 --- a/physics/components/diesel.cpp +++ b/physics/components/diesel.cpp @@ -339,7 +339,7 @@ double physics::Vehicle::DieselElectricTargetRevolutions() 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[protection.PressureSwitchTripped() ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; + tmp = DElist[protection.PressureSwitchTripped() ? MainCtrlNoPowerPos() : mainCtrlPos].RPM / 60.0; if (true == trainHeating.IsAllowed() && trainHeating.config.power > 0 && trainHeating.config.engineRpm > 0) { @@ -383,8 +383,8 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) else // jazda ciapongowa { auto power = Power; - tempImax = DElist[MainCtrlPos].Imax; - tempUmax = DElist[MainCtrlPos].Umax; + tempImax = DElist[mainCtrlPos].Imax; + tempUmax = DElist[mainCtrlPos].Umax; if (true == trainHeating.IsOn()) { power -= trainHeating.config.power; @@ -392,7 +392,7 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) 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)}; + auto const currentgenpower{(DElist[mainCtrlPos].RPM > 0 ? DElist[mainCtrlPos].GenPower * (60.0 * enrot / DElist[mainCtrlPos].RPM) : 0.0)}; tmp = std::min(power, currentgenpower); @@ -435,7 +435,7 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) if (auto const fieldshuntingcontrol{fieldshunting::diesel_electric(AutoRelayType, FieldShuntSwitch, AutoRelayFlag)}; false == lineContactors.IsClosed() || ShuntMode || fieldshuntingcontrol == fieldshunting::control::off) { - ScndCtrlPos = 0; + scndCtrlPos = 0; } else if (AutoRelayFlag) { @@ -444,16 +444,16 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) } } -// the tractive force of a diesel-electric shunting, by the generator's table SST and the shunting controller AnPos; +// 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 physics::Vehicle::DieselElectricShuntForce(double const tmpV, double &tmp) { if (true == lineContactors.IsClosed()) { - EngineVoltage = SST[MainCtrlPos].Umax * AnPos + SST[MainCtrlPos].Umin * (1.0 - AnPos); + 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); + tmp = EngineRPMRatio() * (SST[mainCtrlPos].Pmax * anPos) + SST[mainCtrlPos].Pmin * (1.0 - anPos); Ft = tmp * 1000.0 / (abs(tmpV) + 1.6); } else @@ -527,7 +527,7 @@ void physics::Vehicle::DieselElectricGenerator(double const tmp, double const te } else { - auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimic_real) : MainCtrlPos; + 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); @@ -557,11 +557,11 @@ void physics::Vehicle::DieselElectricGenerator(double const tmp, double const te // the current of a diesel-electric vehicle's traction motors giving the moment [N m] of one motor double physics::Vehicle::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); + // 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)); + 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 @@ -721,7 +721,7 @@ bool physics::Vehicle::dizel_AutoGearCheck(void) bool physics::Vehicle::dizel_GearShiftCheck(double const VelUp, double const VelDown) { auto OK{false}; - if (RList[MainCtrlPos].Mn == 0 && !torqueConverter.present) + if (RList[mainCtrlPos].Mn == 0 && !torqueConverter.present) { if (diesel.clutchState > 0) dizel_EngageSwitch(0); @@ -787,13 +787,13 @@ void physics::Vehicle::dizel_ClutchCheck() if (!(motor_param(ScndCtrlActualPos).mIsat > 0)) dizel_EngageSwitch(0.0); // wylacz sprzeglo na pozycjach neutralnych if (!AutoRelayFlag) - ScndCtrlActualPos = ScndCtrlPos; + ScndCtrlActualPos = scndCtrlPos; } // the clutch by the controller's position: half or fully in, fully over the speed of the full engagement void physics::Vehicle::dizel_ClutchByController() { - switch (RList[MainCtrlPos].Mn) + switch (RList[mainCtrlPos].Mn) { case 1: dizel_EngageSwitch(0.5); @@ -817,7 +817,7 @@ void physics::Vehicle::dizel_ClutchByController() if (Vel > diesel.fullEngageMinVelocity) dizel_EngageSwitch(1.0); else - dizel_EngageSwitch(0.35 * (1 + RList[MainCtrlPos].R) * RList[MainCtrlPos].R); + dizel_EngageSwitch(0.35 * (1 + RList[mainCtrlPos].R) * RList[mainCtrlPos].R); break; default: if (torqueConverter.present && torqueConverter.fill > 0.01) @@ -851,7 +851,7 @@ bool physics::Vehicle::dizel_StartupCheck() // test the fuel pump // TODO: add fuel pressure check - if (false == FuelPump.is_active || (EngineType == TEngineType::DieselEngine && RList[MainCtrlPos].R == 0.0)) + if (false == FuelPump.is_active || (EngineType == TEngineType::DieselEngine && RList[mainCtrlPos].R == 0.0)) { engineisready = false; // if( FuelPump.start_type == start_t::manual ) { @@ -932,7 +932,7 @@ bool physics::Vehicle::dizel_Update(double dt) dizel_EngageChange(dt); DU = dizel_AutoGearCheck(); double const fillspeed{2}; - diesel.fill = diesel.fill + fillspeed * dt * (dizel_fillcheck(MainCtrlPos, dt) - diesel.fill); + diesel.fill = diesel.fill + fillspeed * dt * (dizel_fillcheck(mainCtrlPos, dt) - diesel.fill); } dizel_Heat(dt); @@ -960,7 +960,7 @@ double physics::Vehicle::dizel_fillcheck(int mcp, double dt) } else { - // napelnienie zalezne od MainCtrlPos + // napelnienie zalezne od mainCtrlPos if (EIMCtrlType > 0) { realfill = dizel_DigitalFill(dt); @@ -1027,7 +1027,7 @@ double physics::Vehicle::dizel_GovernorFill(int const mcp, double realfill) cons double physics::Vehicle::dizel_GovernorRevolutions(int const mcp, double &realfill) const { auto nreg{0.0}; - switch (RList[MainCtrlPos].Mn) + switch (RList[mainCtrlPos].Mn) { case 0: case 1: diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index 5ff81e000..fc489a3a9 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -136,8 +136,8 @@ bool increaseNotch(physics::Vehicle &vehicle, int const speed) { return vehicle.IncMainCtrl(1) && vehicle.IncMainCtrl(speed - 1); // a fail will propagate up the recursion chain. should this be || instead? } - ++vehicle.MainCtrlPos; - if (vehicle.EIMCtrlType == 0 && (vehicle.SpeedCtrlAutoTurnOffFlag & 1) == 1 && vehicle.MainCtrlActualPos != vehicle.MainCtrlPos) + vehicle.SetMainCtrlPos(vehicle.MainCtrlPos() + 1); + if (vehicle.EIMCtrlType == 0 && (vehicle.SpeedCtrlAutoTurnOffFlag & 1) == 1 && vehicle.MainCtrlActualPos != vehicle.MainCtrlPos()) { vehicle.SpeedCtrlSwitch(false); vehicle.SpeedCtrlUnit.IsActive = false; @@ -149,8 +149,8 @@ bool decreaseNotch(physics::Vehicle &vehicle, int const speed) { if (speed == 1) { - vehicle.MainCtrlPos--; - if (vehicle.EIMCtrlType == 0 && (vehicle.SpeedCtrlAutoTurnOffFlag & 1) == 1 && vehicle.MainCtrlActualPos != vehicle.MainCtrlPos) + vehicle.SetMainCtrlPos(vehicle.MainCtrlPos() - 1); + if (vehicle.EIMCtrlType == 0 && (vehicle.SpeedCtrlAutoTurnOffFlag & 1) == 1 && vehicle.MainCtrlActualPos != vehicle.MainCtrlPos()) { vehicle.SpeedCtrlSwitch(false); vehicle.SpeedCtrlUnit.IsActive = false; @@ -189,7 +189,7 @@ class DumbDrive final : public TractionDrive public: double UpdateEnginePower(physics::Vehicle &vehicle) const override { - auto const posRatio{(vehicle.MainCtrlPos + vehicle.ScndCtrlPos) / (vehicle.MainCtrlPosNo + vehicle.ScndCtrlPosNo + 0.01)}; + auto const posRatio{(vehicle.MainCtrlPos() + vehicle.ScndCtrlPos()) / (vehicle.MainCtrlPosNo + vehicle.ScndCtrlPosNo + 0.01)}; vehicle.EnginePower = /*1000.0 **/ vehicle.Power * posRatio; return posRatio; } @@ -365,7 +365,7 @@ public: double UpdateEngineRevolutions(physics::Vehicle &vehicle, double const dt, double &transmission, double &moment) const override { if (vehicle.ShuntMode) // dodatkowa przekładnia np. dla 2Ls150 - transmission = vehicle.AnPos * vehicle.Transmision.Ratio * vehicle.motor_param(vehicle.ScndCtrlActualPos).mIsat; + transmission = vehicle.AnPos() * vehicle.Transmision.Ratio * vehicle.motor_param(vehicle.ScndCtrlActualPos).mIsat; else transmission = vehicle.Transmision.Ratio * vehicle.motor_param(vehicle.ScndCtrlActualPos).mIsat; @@ -376,14 +376,14 @@ public: { if (speed > 1) { - while (vehicle.MainCtrlPos < vehicle.MainCtrlPosNo && vehicle.IncMainCtrl(1)) + while (vehicle.MainCtrlPos() < vehicle.MainCtrlPosNo && vehicle.IncMainCtrl(1)) { // all work is done in the loop header } } else { - ++vehicle.MainCtrlPos; + vehicle.SetMainCtrlPos(vehicle.MainCtrlPos() + 1); } vehicle.air.compressor.Allow(vehicle.MainCtrlPowerPos() > 0); return true; @@ -392,12 +392,12 @@ public: { if (speed == 1) { - vehicle.MainCtrlPos--; + vehicle.SetMainCtrlPos(vehicle.MainCtrlPos() - 1); return true; } if (speed > 1) { - while (vehicle.MainCtrlPos > 0 || vehicle.RList[vehicle.MainCtrlPos].Mn > 0) + while (vehicle.MainCtrlPos() > 0 || vehicle.RList[vehicle.MainCtrlPos()].Mn > 0) vehicle.DecMainCtrl(1); return true; } diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index 0e75ef611..a40ace064 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -863,7 +863,7 @@ bool physics::Vehicle::MainSwitchCheck() const powerisavailable = Genset.is_active && Genset.voltage >= TractionSupplyMinVoltage(); } - return powerisavailable && (ScndCtrlPos == 0 || EngineType == ElectricInductionMotor) && lineBreaker.IsInitialised() && + return powerisavailable && (scndCtrlPos == 0 || EngineType == ElectricInductionMotor) && lineBreaker.IsInitialised() && (converter.IsOverloaded() == false || converter.config.overloadRelayOffWithLineBreaker) && true == protection.GroundHolds() && (true == protection.UndervoltageHolds() || lineBreaker.config.pantographsRequireIt) && true == protection.OvervoltageHolds() && LastSwitchingTime > CtrlDelay && (HasCamshaft ? IsMainCtrlActualNoPowerPos() : diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index f4a3e934e..0aa4ce4f6 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -1302,15 +1302,15 @@ void physics::Vehicle::LoadFIZ_EngineDiesel(std::string const &Input) extract_value(engageupspeed, "EUS", Input, "0.5"); extract_value(engagedownspeed, "EDS", Input, "0.9"); - if (true == extract_value(AnPos, "ShuntMode", Input, "")) + if (true == extract_value(anPos, "ShuntMode", Input, "")) { // dodatkowa przekładnia dla SM03 (2Ls150) ShuntModeAllow = true; ShuntMode = false; - if (AnPos < 1.0) + if (anPos < 1.0) { //"rozruch wysoki" ma dawać większą siłę - AnPos = 1.0 / AnPos; // im większa liczba, tym wolniej jedzie + anPos = 1.0 / anPos; // im większa liczba, tym wolniej jedzie } } extract_value(torqueConverter.present, "IsTC", Input, ""); @@ -1365,7 +1365,7 @@ void physics::Vehicle::LoadFIZ_EngineDieselElectric(std::string const &Input) ShuntModeAllow = true; ShuntMode = false; - AnPos = 0.0; + anPos = 0.0; ImaxHi = 2; ImaxLo = 1; } diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 7abac3c67..146557cf0 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -571,7 +571,7 @@ bool physics::Vehicle::SwitchEPBrake(int state) bool OK; OK = false; - if (brakes.config.driverValveType == TBrakeHandle::St113 && CabOccupied != 0) + if (brakes.config.driverValveType == TBrakeHandle::St113 && cabOccupied != 0) { // the handle works the EP contactors pneumatically, their supply is cut as the Oerlikon handle's is if (state > 0 && EPBrakeControlPowered()) @@ -840,11 +840,11 @@ void physics::Vehicle::UpdatePipePressure(double dt) UpdateDistributorSettings(); - if ((brakes.config.driverValveType == TBrakeHandle::FVel6 || brakes.config.driverValveType == TBrakeHandle::FVE408) && CabOccupied != 0) + if ((brakes.config.driverValveType == TBrakeHandle::FVel6 || brakes.config.driverValveType == TBrakeHandle::FVE408) && cabOccupied != 0) { UpdateEPBrake(); } - else if (brakes.config.driverValveType == TBrakeHandle::St113 && CabOccupied != 0 && std::abs(EpForce) > 0.001 && !EPBrakeControlPowered()) + else if (brakes.config.driverValveType == 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); @@ -932,7 +932,7 @@ void physics::Vehicle::UpdateMainValve(double dt) // the driver's valve of a vehicle prepared for hauling is cut out, whatever its handle shows brakes.driverValveFlow = 0; } - else if ((brakes.config.availableOperatingModes & bom_PS) == 0 || (CabOccupied != 0 && brakes.operatingMode != bom_PS)) + else if ((brakes.config.availableOperatingModes & bom_PS) == 0 || (cabOccupied != 0 && brakes.operatingMode != bom_PS)) { if (brakes.operatingMode < bom_EP || brakes.driverValve->GetPos(bh_EB) - 0.5 < brakes.handlePositionReal || (brakes.config.driverValveType != TBrakeHandle::MHZ_EN57 && brakes.config.driverValveType != TBrakeHandle::MHZ_K8P)) @@ -1002,7 +1002,7 @@ void physics::Vehicle::UpdateEmergencyValve(double dt) // 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 && brakes.independentPosition >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || + auto const ownemergency{radioStopFlag || (EIMCtrlEmergency && brakes.independentPosition >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || (brakes.spring.driveEmergencySpeed >= 0 && Vel > brakes.spring.driveEmergencySpeed && brakes.spring.isActive) || (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)}; if (brakes.alarmChain || (ownemergency && false == PulleeMode)) diff --git a/physics/components/securitysystem.cpp b/physics/components/securitysystem.cpp index d42ef208a..051413cdf 100644 --- a/physics/components/securitysystem.cpp +++ b/physics/components/securitysystem.cpp @@ -253,7 +253,7 @@ void physics::Vehicle::SecuritySystemCheck(double dt) SecuritySystem.set_shunt_mode(ShuntMode); SecuritySystem.update(dt, Vel, isPower, CabActive); - if (!lowVoltage.IsBatteryOn() || !Radio || !RadioFuse) + if (!lowVoltage.IsBatteryOn() || !radio || !radioFuse) { // wyłączenie baterii deaktywuje sprzęt RadiostopSwitch(false); } @@ -269,9 +269,9 @@ bool physics::Vehicle::RadiostopSwitch(bool Switch) if (brakes.config.kind != TBrakeSystem::Individual && brakes.config.handlePositions > 0) { - if (true == Switch && false == RadioStopFlag) + if (true == Switch && false == radioStopFlag) { - RadioStopFlag = Switch; + radioStopFlag = Switch; EBS = true; } else @@ -279,7 +279,7 @@ bool physics::Vehicle::RadiostopSwitch(bool Switch) if (Switch == false && std::abs(V) < 0.1) { // odblokowanie hamulca bezpieczenistwa tylko po zatrzymaniu - RadioStopFlag = Switch; + radioStopFlag = Switch; EBS = true; } else diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index aea52146f..c3c275366 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -91,7 +91,7 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) CreateBrakePipes(); if (LightsPosNo > 0) - LightsPos = LightsDefPos; + lightsPos = LightsDefPos; // set default wiper switch position wiperSwitchPos = WiperDefaultPos; diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index 137dd1446..d454b62cd 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -613,7 +613,7 @@ void physics::Vehicle::UpdateResistorBlowers(double dt) case 1: { // manual - if (true == RVentForceOn || (DirActive != 0 && RList[MainCtrlActualPos].R > RVentCutOff)) + if (true == rventForceOn || (DirActive != 0 && RList[MainCtrlActualPos].R > RVentCutOff)) { RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; } @@ -636,7 +636,7 @@ void physics::Vehicle::UpdateResistorBlowers(double dt) { RventRot += (RVentnmax * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; } - else if (RVentForceOn) + else if (rventForceOn) { RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; } @@ -796,7 +796,7 @@ void physics::Vehicle::SeriesMotorDynamicBrake(double dt) // power (tmp, the power the engine gives) void physics::Vehicle::ShuntFieldRelaysCheck(double const tmpV, double const PosRatio, double const tmp) { - auto const shuntfieldstate{ScndCtrlPos}; + auto const shuntfieldstate{scndCtrlPos}; switch (RelayType) { @@ -804,26 +804,26 @@ void physics::Vehicle::ShuntFieldRelaysCheck(double const tmpV, double const Pos case 0: { - if (ScndCtrlPos < ScndCtrlPosNo && Im <= MPTRelay[ScndCtrlPos].Iup * PosRatio) + if (scndCtrlPos < ScndCtrlPosNo && Im <= MPTRelay[scndCtrlPos].Iup * PosRatio) { - ++ScndCtrlPos; + ++scndCtrlPos; } - if (ScndCtrlPos > 0 && Im >= MPTRelay[ScndCtrlPos].Idown * PosRatio) + if (scndCtrlPos > 0 && Im >= MPTRelay[scndCtrlPos].Idown * PosRatio) { - --ScndCtrlPos; + --scndCtrlPos; } break; } case 1: { - if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel) + if (scndCtrlPos < ScndCtrlPosNo && MPTRelay[scndCtrlPos].Iup < Vel) { - ++ScndCtrlPos; + ++scndCtrlPos; } - if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown > Vel) + if (scndCtrlPos > 0 && MPTRelay[scndCtrlPos].Idown > Vel) { - --ScndCtrlPos; + --scndCtrlPos; } break; } @@ -854,7 +854,7 @@ void physics::Vehicle::ShuntFieldRelaysCheck(double const tmpV, double const Pos } } // switch RelayType - if (ScndCtrlPos != shuntfieldstate) + if (scndCtrlPos != shuntfieldstate) { SetFlag(SoundFlag, sound::relay | sound::shuntfield); } @@ -863,80 +863,80 @@ void physics::Vehicle::ShuntFieldRelaysCheck(double const tmpV, double const Pos // 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 physics::Vehicle::ShuntFieldRelaysType2(double const tmp) { - if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) + if (scndCtrlPos < ScndCtrlPosNo && MPTRelay[scndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) { - ++ScndCtrlPos; + ++scndCtrlPos; } - if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown < Im) + if (scndCtrlPos > 0 && MPTRelay[scndCtrlPos].Idown < Im) { - --ScndCtrlPos; + --scndCtrlPos; } } // the relays of type 41: up by the speed tmpV at full power, the engine slowed down, down by the current void physics::Vehicle::ShuntFieldRelaysType41(double const tmpV) { - if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[ScndCtrlPos].Iup) + if (scndCtrlPos < ScndCtrlPosNo && mainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[scndCtrlPos].Iup) { - ++ScndCtrlPos; + ++scndCtrlPos; enrot = enrot * 0.73; } - if (ScndCtrlPos > 0 && Im > MPTRelay[ScndCtrlPos].Idown) + if (scndCtrlPos > 0 && Im > MPTRelay[scndCtrlPos].Idown) { - --ScndCtrlPos; + --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 physics::Vehicle::ShuntFieldRelaysType45() { - if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos >= 11) + if (scndCtrlPos < ScndCtrlPosNo && mainCtrlPos >= 11) { - if (Im < MPTRelay[ScndCtrlPos].Iup) + if (Im < MPTRelay[scndCtrlPos].Iup) { - ++ScndCtrlPos; + ++scndCtrlPos; } // check for cases where the speed drops below threshold for level 2 or 3 - if (ScndCtrlPos > 1 && Vel < MPTRelay[ScndCtrlPos - 1].Idown) + if (scndCtrlPos > 1 && Vel < MPTRelay[scndCtrlPos - 1].Idown) { - --ScndCtrlPos; + --scndCtrlPos; } } // malenie - if (ScndCtrlPos > 0 && MainCtrlPos < 11) + if (scndCtrlPos > 0 && mainCtrlPos < 11) { - if (ScndCtrlPos == 1) + if (scndCtrlPos == 1) { - if (Im > MPTRelay[ScndCtrlPos - 1].Idown) + if (Im > MPTRelay[scndCtrlPos - 1].Idown) { - --ScndCtrlPos; + --scndCtrlPos; } } else { - if (Vel < MPTRelay[ScndCtrlPos].Idown) + if (Vel < MPTRelay[scndCtrlPos].Idown) { - --ScndCtrlPos; + --scndCtrlPos; } } } // 3rd level drops with master controller at position lower than 10... - if (MainCtrlPos < 11) + if (mainCtrlPos < 11) { - ScndCtrlPos = std::min(2, ScndCtrlPos); + scndCtrlPos = std::min(2, scndCtrlPos); } // ...and below position 7 field shunt drops altogether - if (MainCtrlPos < 8) + if (mainCtrlPos < 8) { - ScndCtrlPos = 0; + 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, + ( DElist[ mainCtrlPos ].RPM / ( enrot * 60.0 ) - 1.0 ) * 50.0, 0.0, 1.0 ) }; */ } @@ -946,22 +946,22 @@ void physics::Vehicle::ShuntFieldRelaysType45() void physics::Vehicle::ShuntFieldRelaysType46() { // wzrastanie - if (MainCtrlPos >= 12 && ScndCtrlPos < ScndCtrlPosNo) + if (mainCtrlPos >= 12 && scndCtrlPos < ScndCtrlPosNo) { ShuntFieldRelaysType46Up(); } // malenie - if (MainCtrlPos < 12 && ScndCtrlPos > 0 && Vel < 50.0) + if (mainCtrlPos < 12 && scndCtrlPos > 0 && Vel < 50.0) { ShuntFieldRelaysType46Down(); } - if (MainCtrlPos < 11) + if (mainCtrlPos < 11) { - ScndCtrlPos = std::min(2, ScndCtrlPos); + scndCtrlPos = std::min(2, scndCtrlPos); } - if (MainCtrlPos < 8) + if (mainCtrlPos < 8) { - ScndCtrlPos = 0; + scndCtrlPos = 0; } } @@ -969,18 +969,18 @@ void physics::Vehicle::ShuntFieldRelaysType46() void physics::Vehicle::ShuntFieldRelaysType46Down() { // above 50 km/h already active shunt field can be maintained until lower controller setting - if (ScndCtrlPos % 2 == 0) + if (scndCtrlPos % 2 == 0) { - if (MPTRelay[ScndCtrlPos].Idown < Im) + if (MPTRelay[scndCtrlPos].Idown < Im) { - --ScndCtrlPos; + --scndCtrlPos; } } else { - if (MPTRelay[ScndCtrlPos + 1].Idown < Im && MPTRelay[ScndCtrlPos].Idown > Vel) + if (MPTRelay[scndCtrlPos + 1].Idown < Im && MPTRelay[scndCtrlPos].Idown > Vel) { - --ScndCtrlPos; + --scndCtrlPos; } } } @@ -988,18 +988,18 @@ void physics::Vehicle::ShuntFieldRelaysType46Down() // a relay of type 46 up: an even one by the current, an odd one by the current and the speed void physics::Vehicle::ShuntFieldRelaysType46Up() { - if (ScndCtrlPos % 2 == 0) + if (scndCtrlPos % 2 == 0) { - if (MPTRelay[ScndCtrlPos].Iup > Im) + if (MPTRelay[scndCtrlPos].Iup > Im) { - ++ScndCtrlPos; + ++scndCtrlPos; } } else { - if (MPTRelay[ScndCtrlPos - 1].Iup > Im && MPTRelay[ScndCtrlPos].Iup < Vel) + if (MPTRelay[scndCtrlPos - 1].Iup > Im && MPTRelay[scndCtrlPos].Iup < Vel) { - ++ScndCtrlPos; + ++scndCtrlPos; } } } @@ -1069,18 +1069,18 @@ void physics::Vehicle::InductionMotorSpeedControl(double dt) // the speed control set by the position of the second controller, after it's been held for its delay void physics::Vehicle::SpeedControlByPosition(double dt) { - if (ScndCtrlPos != NewSpeed) + if (scndCtrlPos != NewSpeed) { SpeedCtrlTimer = 0; - NewSpeed = ScndCtrlPos; + NewSpeed = scndCtrlPos; } else { SpeedCtrlTimer += dt; if (SpeedCtrlTimer > SpeedCtrlDelay) { - auto NewSCAP = static_cast((float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax); + auto NewSCAP = static_cast((float)scndCtrlPos / (float)ScndCtrlPosNo * Vmax); if (NewSCAP != SpeedCtrlValue) { SpeedCtrlValue = NewSCAP; @@ -1096,7 +1096,7 @@ void physics::Vehicle::SpeedControlByPosition(double dt) void physics::Vehicle::SpeedControlByTime(double dt) { SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; - switch (ScndCtrlPos) + switch (scndCtrlPos) { case 0: NewSpeed = 0; @@ -1174,7 +1174,7 @@ void physics::Vehicle::InductionMotorBrakeBlending(double const ActiveInverters, void physics::Vehicle::InductionMotorDynamicBrakeFlag() { double const edBCP = brakes.distributor->GetEDBCP(); - auto const localbrakeactive{CabOccupied != 0 && brakes.independentValve->GetCP() > 0.25}; + auto const localbrakeactive{cabOccupied != 0 && brakes.independentValve->GetCP() > 0.25}; // gdy SplitEDPneumaticBrake jest aktywne, hamulec pomocniczy (LocalBrake) NIE wymusza // zalaczenia hamulca elektrodynamicznego - ED jest sterowany wlasnym nastawnikiem auto const dynbrakectrlactive{brakes.electrodynamic.splitFromPneumatic && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; @@ -1184,10 +1184,10 @@ void physics::Vehicle::InductionMotorDynamicBrakeFlag() { brakes.electrodynamic.on = true; } - else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && AnPos < 0.01) || + else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && anPos < 0.01) || (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && brakes.independentPosition < 0.01)) brakes.electrodynamic.on = false; - else if (brakes.cylinderPressure > 0.25 && edBCP > 0.25 || localbrakeforED || AnPos > 0.02 || dynbrakectrlactive) + else if (brakes.cylinderPressure > 0.25 && edBCP > 0.25 || localbrakeforED || anPos > 0.02 || dynbrakectrlactive) brakes.electrodynamic.on = true; } @@ -1225,12 +1225,12 @@ double physics::Vehicle::InductionMotorBrakeRatio(double const ActiveInverters, // 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 / brakes.config.maxCylinderPressure[0], 1.0)), AnPos) * vhRamp; + PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / brakes.config.maxCylinderPressure[0], 1.0)), anPos) * vhRamp; inductionMotor.state.forceDemand = -std::min(1.0, std::max(edLeverDemand, edBCP / brakes.config.maxCylinderPressure[0])); } else { - PosRatio = -std::max(std::min(edBCP * 1.0 / brakes.config.maxCylinderPressure[0], 1.0), AnPos) * vhRamp; + PosRatio = -std::max(std::min(edBCP * 1.0 / brakes.config.maxCylinderPressure[0], 1.0), anPos) * vhRamp; inductionMotor.state.forceDemand = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / brakes.config.maxCylinderPressure[0])); } } @@ -1461,14 +1461,14 @@ bool physics::Vehicle::RelayReset(int const Relays, range_t const Notify) bool reset{false}; if (TestFlag(Relays, relay_t::maincircuitground) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && - (protection.config.groundStart == start_t::manual || protection.config.groundStart == start_t::manualwithautofallback) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && + (protection.config.groundStart == start_t::manual || protection.config.groundStart == start_t::manualwithautofallback) && IsMainCtrlNoPowerPos() && scndCtrlPos == 0 && DirActive != 0 && false == equipmentFaults.HasAll(EquipmentFault::differentialRelay)) { // NOTE: true means the relay is operational reset |= protection.ResetGround(lowvoltagepower); } - if (TestFlag(Relays, relay_t::tractionnmotoroverload) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && + if (TestFlag(Relays, relay_t::tractionnmotoroverload) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && IsMainCtrlNoPowerPos() && scndCtrlPos == 0 && DirActive != 0 && false == equipmentFaults.HasAll(EquipmentFault::differentialRelay)) { // NOTE: false means the relay is operational diff --git a/physics/consistbraking.cpp b/physics/consistbraking.cpp index 22b38570e..a718a6624 100644 --- a/physics/consistbraking.cpp +++ b/physics/consistbraking.cpp @@ -63,7 +63,7 @@ void physics::ConsistBrakeBlending::SetControl(Step &state, Vehicle &Lead, Input // 0a. ustal aktualna nastawe zadania sily napedowej i hamowania if( Lead.Power < 1 && Given.owner != nullptr ) { - Lead.MainCtrlPos = Given.owner->MainCtrlPos*Lead.MainCtrlPosNo / std::max(1, Given.owner->MainCtrlPosNo); + Lead.SetMainCtrlPos(Given.owner->MainCtrlPos()*Lead.MainCtrlPosNo / std::max(1, Given.owner->MainCtrlPosNo)); Lead.SpeedCtrlValue = Given.owner->SpeedCtrlValue; Lead.SpeedCtrlUnit.IsActive = Given.owner->SpeedCtrlUnit.IsActive; } @@ -73,7 +73,7 @@ void physics::ConsistBrakeBlending::SetControl(Step &state, Vehicle &Lead, Input state.eimic = std::min(Lead.eimic, Lead.eimicSpeedCtrl); Lead.eimic_real = state.eimic; // Elf: full braking at once in the lowest position, and in the emergency brake position below it - if (Lead.EIMCtrlType == 2 && Lead.MainCtrlPos <= Lead.EIMCtrlEmergencyPositions()) + if (Lead.EIMCtrlType == 2 && Lead.MainCtrlPos() <= Lead.EIMCtrlEmergencyPositions()) state.eimic = -1.0; Lead.SendCtrlToNext(VehicleCommand::integratedController, std::max(0., state.eimic), Lead.CabActive); state.LBR = std::max(-state.eimic, 0.); @@ -221,7 +221,7 @@ void physics::ConsistBrakeBlending::ComputeElectrodynamicDemand(Step &state, Veh state.FzadED = std::min( state.Fzad, state.FmaxED ); } /*/ELF - wdrazanie ED po powrocie na utrzymanie hamowania - do usuniecia - if (Lead.EIMCtrlType == 2 && Lead.MainCtrlPos < 2 && Lead.eimic > -0.999) + if (Lead.EIMCtrlType == 2 && Lead.MainCtrlPos() < 2 && Lead.eimic > -0.999) { FzadED = std::min(FzadED, lastEdDemand); } //*/ @@ -267,7 +267,7 @@ void physics::ConsistBrakeBlending::DistributeForces(Step &state, Vehicle const // 6. ustaw pojazdom sile hamowania ep // - proporcjonalnie do masy, do liczby osi, rowne cisnienia - jak // bedzie, tak bedzie dobrze - float Fpoj = 0; // Lead.CabOccupied < 0 + float Fpoj = 0; // Lead.CabOccupied() < 0 ////ALGORYTM 2 - KAZDEMU PO ROWNO, ale nie wiecej niz eped * masa // 1. najpierw daj kazdemu tyle samo int i = 0; @@ -286,8 +286,7 @@ void physics::ConsistBrakeBlending::DistributeForces(Step &state, Vehicle const PrzekrF[i] = false; FzED[i] = state.FmaxED > 0 ? state.FzadED / state.FmaxED : 0; - vehicle->AnPos = - Lead.ScndS ? state.LBR : FzED[i]; + vehicle->SetAnPos(Lead.ScndS ? state.LBR : FzED[i]); FzEP[ i ] = static_cast( state.FzadPN * vehicle->NAxles ) / static_cast( state.osie ); ++i; vehicle->ShuntMode = Lead.ShuntMode; diff --git a/physics/vehicle.h b/physics/vehicle.h index ef6bd1557..c733973c2 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -649,11 +649,14 @@ class Vehicle double LightPower = 0.0; /*moc pobierana na ogrzewanie/oswietlenie*/ bool EpFuse = true; /*Czy jest wlaczony hamulec EP*/ double EpForce = 0.0; /*Poziom zadanej sily EP*/ - bool Signalling = false; /*Czy jest zalaczona sygnalizacja hamowania ostatniego wagonu*/ - bool Radio = false; /*Czy jest zalaczony radiotelefon*/ + bool const &Signalling() const { return signalling; } /*Czy jest zalaczona sygnalizacja hamowania ostatniego wagonu*/ + void SetSignalling(bool const Value) { signalling = Value; } + bool const &Radio() const { return radio; } /*Czy jest zalaczony radiotelefon*/ + void SetRadio(bool const Value) { radio = Value; } // the cut-off in the radio's power supply: a fuse in the cabinet, a lever on the desk or the switch on the radio's power // supply (eu07/maszyna#438). Closed unless the driver opens it, so vehicles without such a switch work as before - bool RadioFuse = true; + bool const &RadioFuse() const { return radioFuse; } + void SetRadioFuse(bool const Value) { radioFuse = Value; } TDimension Dim; /*wymiary*/ double Cx = 0.0; /*wsp. op. aerodyn.*/ float Floor = 0.96f; // poziom podłogi dla ładunków @@ -673,7 +676,8 @@ class Vehicle double BDist = 0.0; /*odlegosc osi oraz czopow skretu*/ int SandCapacity = 0; /*zasobnik piasku [kg]*/ - int wiperSwitchPos = 0; // pozycja przelacznika wycieraczek + int const &WiperSwitchPos() const { return wiperSwitchPos; } // pozycja przelacznika wycieraczek + void SetWiperSwitchPos(int const Value) { wiperSwitchPos = Value; } double WiperAngle = {45.0}; // kat pracy wycieraczek LowVoltageSupply lowVoltage; // the battery and the low voltage circuits (physics/components/lowvoltage.h) @@ -713,9 +717,9 @@ class Vehicle bool isDoubleClickForMeasureNeeded = {false}; // czy rozpoczecie pomiaru odleglosci odbywa sie po podwojnym wcisnienciu przycisku? float DistanceCounterDoublePressPeriod = {1.f}; // czas w jakim nalezy podwojnie wcisnac przycisk, aby rozpoczac pomiar odleglosci TSecuritySystem SecuritySystem; - int EmergencyBrakeWarningSignal{0}; // combined with basic WarningSignal when manual emergency brake is active - horn_supply HornSupply{horn_supply::air}; // of the low and high tone horns (WarningSignal 1 and 2) - horn_supply Horn3Supply{horn_supply::air}; // of the third horn (WarningSignal 4) + int EmergencyBrakeWarningSignal{0}; // combined with basic warningSignal when manual emergency brake is active + horn_supply HornSupply{horn_supply::air}; // of the low and high tone horns (warningSignal 1 and 2) + horn_supply Horn3Supply{horn_supply::air}; // of the third horn (warningSignal 4) // main reservoir pressure [bar, as MinCP and MaxCP] below which a pneumatic horn stays silent static constexpr double HornMinPressure{2.0}; TUniversalCtrlTable UniCtrlList; /*lista pozycji uniwersalnego nastawnika*/ @@ -807,7 +811,8 @@ class Vehicle double RVentCutOff = 0.0; /*rezystancja wylaczania wentylatorow dla RVentType=2*/ double RVentSpeed{0.5}; // rozpedzanie sie wentylatora obr/s^2} double RVentMinI{50.0}; // przy jakim pradzie sie wylaczaja} - bool RVentForceOn{false}; // forced activation switch + bool const &RVentForceOn() const { return rventForceOn; } // forced activation switch + void SetRVentForceOn(bool const Value) { rventForceOn = Value; } bool Trafo = false; /*pojazd wyposażony w transformator*/ // the diesel engine, its torque converter and its retarder (physics/components/dieselengine.h) @@ -817,7 +822,8 @@ class Vehicle double engagedownspeed = 0.9; double engageupspeed = 0.5; /*- dla lokomotyw spalinowo-elektrycznych -*/ - double AnPos = 0.0; // pozycja sterowania dokladnego (analogowego) + double const &AnPos() const { return anPos; } // pozycja sterowania dokladnego (analogowego) + void SetAnPos(double const Value) { anPos = Value; } bool AnalogCtrl = false; // bool AnMainCtrl = false; // bool ShuntModeAllow = false; @@ -879,7 +885,8 @@ class Vehicle #endif double MirrorMaxShift{90.0}; double MirrorVelClose{5.0}; - bool MirrorForbidden{false}; /*czy jest pozwolenie na otworzenie lusterek (przycisk)*/ + bool const &MirrorForbidden() const { return mirrorForbidden; } /*czy jest pozwolenie na otworzenie lusterek (przycisk)*/ + void SetMirrorForbidden(bool const Value) { mirrorForbidden = Value; } bool ScndS = false; /*Czy jest bocznikowanie na szeregowej*/ bool ScndCtrlResistiveLock{false}; // the shunt controller can't be moved, up or down, while the master controller is at zero or on a resistive position, and drops to 0 when the master controller gets there (ScndCtrlResistiveLock=Yes in Cntrl.) bool SpeedCtrl = false; /*czy jest tempomat*/ @@ -954,7 +961,8 @@ class Vehicle /* */ - bool RadioStopFlag = false; /*hamowanie nagle*/ + bool const &RadioStopFlag() const { return radioStopFlag; } /*hamowanie nagle*/ + void SetRadioStopFlag(bool const Value) { radioStopFlag = Value; } int TUHEX_StageActual = 0; /*aktualny stopien tuhexa*/ bool TUHEX_ResChange = false; /*czy zmiana rezystancji hamowania ED - odwzbudzanie*/ bool TUHEX_Active = false; /*czy hamowanie ED wywołane z zewnątrz*/ @@ -977,27 +985,32 @@ class Vehicle /*-zmienne dla lokomotyw*/ bool ReleaserEnabledOnlyAtNoPowerPos{false}; - int MainCtrlPos = 0; /*polozenie glownego nastawnika*/ - int ScndCtrlPos = 0; /*polozenie dodatkowego nastawnika*/ - int LightsPos = 0; /*polozenie przelacznika wielopozycyjnego swiatel*/ + int const &MainCtrlPos() const { return mainCtrlPos; } /*polozenie glownego nastawnika*/ + void SetMainCtrlPos(int const Value) { mainCtrlPos = Value; } + int const &ScndCtrlPos() const { return scndCtrlPos; } /*polozenie dodatkowego nastawnika*/ + void SetScndCtrlPos(int const Value) { scndCtrlPos = Value; } + int const &LightsPos() const { return lightsPos; } /*polozenie przelacznika wielopozycyjnego swiatel*/ + void SetLightsPos(int const Value) { lightsPos = Value; } int DirActive = 0; // czy lok. jest wlaczona i w ktorym kierunku: względem wybranej kabiny: -1 - do tylu, +1 - do przodu, 0 - wylaczona int DirAbsolute = 0; // zadany kierunek jazdy względem sprzęgów (1=w strone 0,-1=w stronę 1) int MainCtrlMaxDirChangePos{0}; // can't change reverser state with master controller set above this position 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 + int const &CabOccupied() const { return cabOccupied; } // numer kabiny, w ktorej jest obsada (zwykle jedna na skład) // TODO: move to TController + void SetCabOccupied(int const Value) { cabOccupied = Value; } 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; + return CabActive == cabOccupied && CabMaster; } // czy aktualna kabina jest na pewno tą, z której można sterować bool AutomaticCabActivation = true; // czy zmostkowany rozrzad przelacza sie sam przy zmianie kabiny int InactiveCabFlag = 0; // co sie dzieje przy dezaktywacji kabiny bool InactiveCabPantsCheck = false; // niech DynamicObject sprawdzi pantografy double LastSwitchingTime = 0.0; /*czas ostatniego przelaczania czegos*/ - int WarningSignal = 0; // 0: nie trabi, 1,2,4: trabi + int const &WarningSignal() const { return warningSignal; } // 0: nie trabi, 1,2,4: trabi + void SetWarningSignal(int const Value) { warningSignal = Value; } bool DepartureSignal = false; /*sygnal odjazdu*/ bool InsideConsist = false; /*-zmienne dla lokomotywy elektrycznej*/ @@ -1116,7 +1129,8 @@ class Vehicle std::vector dimPositions = {{false, false, false}, // 0 - Not dimmed {false, true, false}}; // 1 - Dimmed - int modernDimmerPosition{0}; + int const &DimmerPosition() const { return modernDimmerPosition; } + void SetDimmerPosition(int const Value) { modernDimmerPosition = Value; } int modernDimmerDefaultPosition{0}; // bool modernContainOffPos{true}; bool enableModernDimmer{false}; @@ -1512,7 +1526,7 @@ class Vehicle // the CouplingType to join the End of this vehicle and the OtherEnd of the other one with, without the control coupling // when ControlCouplingAllowed() rules it out. a permanent coupling (of the vehicles of one unit) is kept whole CouplingSet CompatibleCoupling(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd, CouplingSet const CouplingType) const; - // the horns of the Signal (WarningSignal bits) which have the air or the voltage they need to sound + // the horns of the Signal (warningSignal bits) which have the air or the voltage they need to sound int SoundingHorns(int const Signal) const; // whether the signal lamps of the main circuit (line contactors, ground relay, motor overload relays) can light: // the pressure switch, when fitted, cuts the start off and puts them out, otherwise they go out once the brakes are applied @@ -1580,7 +1594,7 @@ class Vehicle // whether the radio is switched on, its power supply isn't cut off and it has the low voltage to work bool RadioPowered() const { - return Radio && RadioFuse && (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()); + return radio && radioFuse && (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()); } /*obrot kol uwzgledniajacy poslizg*/ double ComputeRotatingWheel(double WForce, double dt, double n) const; @@ -1774,10 +1788,26 @@ class Vehicle 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 + // 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: + // the switches and the controllers the cab, the AI and the scenery change only through the operations above + bool signalling = false; + bool radio = false; + bool radioFuse = true; + int wiperSwitchPos = 0; + bool rventForceOn{false}; + double anPos = 0.0; + bool mirrorForbidden{false}; + bool radioStopFlag = false; + int mainCtrlPos = 0; + int scndCtrlPos = 0; + int lightsPos = 0; + int cabOccupied = 0; + int warningSignal = 0; + int modernDimmerPosition{0}; + 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; diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 17cc92dad..02b3bf9dd 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -76,9 +76,9 @@ std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle cons return on(Occupied.lowVoltage.IsBatteryOn() || Controlling.lowVoltage.IsBatteryOn(), device::battery) | on(Controlling.lineBreaker.IsClosed(), device::main_breaker) | on(Controlling.pantographs[VehicleEnd::front].is_active, device::pantograph_front) | on(Controlling.pantographs[VehicleEnd::rear].is_active, device::pantograph_rear) | on(Controlling.converter.IsRunning(), device::converter) | on(Controlling.air.compressor.IsRunning(), device::compressor) | on(Controlling.lineContactors.IsClosed(), device::line_contactors) | - on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose, device::sanding) | on(Occupied.WarningSignal != 0, device::horn) | + on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose, device::sanding) | on(Occupied.WarningSignal() != 0, device::horn) | on(false == Occupied.Doors.instances[VehicleSide::left].is_closed, device::doors_left) | - on(false == Occupied.Doors.instances[VehicleSide::right].is_closed, device::doors_right) | on(Occupied.Radio, device::radio) | + on(false == Occupied.Doors.instances[VehicleSide::right].is_closed, device::doors_right) | on(Occupied.Radio(), device::radio) | on(Controlling.trainHeating.IsOn(), device::heating) | on(Occupied.brakes.spring.isActive, device::spring_brake) | on(Controlling.ShuntMode, device::shunt_mode) | // the doors as the cab works them: the permits, the departure signal, the steps and the lock on(Occupied.DepartureSignal, device::departure_signal) | on(Occupied.Doors.instances[VehicleSide::left].open_permit, device::door_permit_left) | @@ -446,9 +446,9 @@ void blackbox_recorder::write_cab() { sample.flags = (FreeFlyModeFlag ? 0 : blackbox::cab_flags::in_cab) | (owner != nullptr && owner->is_active() ? blackbox::cab_flags::ai_valid : 0) | (controlling->SecuritySystem.is_blinking() ? blackbox::cab_flags::alerter_blinking : 0) | (controlling->SecuritySystem.is_beeping() ? blackbox::cab_flags::alerter_beeping : 0) | (controlling->SlippingWheels ? blackbox::cab_flags::wheel_slip : 0) | - (occupied->RadioStopFlag ? blackbox::cab_flags::radio_stop : 0) | (occupied->brakes.alarmChain ? blackbox::cab_flags::alarm_chain : 0); - sample.main_controller = static_cast(controlling->MainCtrlPos); - sample.scnd_controller = static_cast(controlling->ScndCtrlPos); + (occupied->RadioStopFlag() ? blackbox::cab_flags::radio_stop : 0) | (occupied->brakes.alarmChain ? blackbox::cab_flags::alarm_chain : 0); + sample.main_controller = static_cast(controlling->MainCtrlPos()); + sample.scnd_controller = static_cast(controlling->ScndCtrlPos()); sample.reverser = static_cast(controlling->DirActive); sample.train_brake = static_cast(occupied->brakes.handlePositionSmooth); sample.local_brake = static_cast(occupied->brakes.independentPosition); @@ -471,7 +471,7 @@ void blackbox_recorder::write_cab() { sample.security = static_cast((security.is_vigilance_blinking() ? flag::vigilance : 0) | (security.is_cabsignal_blinking() ? flag::cabsignal : 0) | (security.is_beeping() ? flag::vigilance_beeping : 0) | (security.is_cabsignal_beeping() ? flag::cabsignal_beeping : 0) | (security.is_braking() ? flag::braking : 0)); - sample.cab = static_cast(occupied->CabOccupied); + sample.cab = static_cast(occupied->CabOccupied()); // what drives the train, the setting of the brakes, the radio, the engine's oil and temperatures sample.engine = engine_of(*controlling); sample.brake_delay = static_cast(occupied->brakes.delaySetting); @@ -487,7 +487,7 @@ void blackbox_recorder::write_cab() { sample.engine_power = static_cast(controlling->EnginePower); sample.hand_brake = static_cast(std::clamp(occupied->brakes.handBrakePosition, -128, 127)); sample.brake_mode = static_cast(occupied->brakes.operatingMode); - sample.horn = static_cast(occupied->WarningSignal); + sample.horn = static_cast(occupied->WarningSignal()); sample.integrated_controller = static_cast(controlling->eimic); sample.clutch = static_cast(controlling->diesel.clutchState); sample.converter_fill = static_cast(controlling->torqueConverter.fill); @@ -528,7 +528,7 @@ void blackbox_recorder::look_around(bool const Keyframe) { auto *train{simulation::Train}; auto const uservehicle{train != nullptr && train->Dynamic() != nullptr ? vehicle_id(train->Dynamic()) : blackbox::no_vehicle}; auto const userincab{uservehicle != blackbox::no_vehicle && false == FreeFlyModeFlag}; - auto const usercab{uservehicle != blackbox::no_vehicle ? static_cast(train->Dynamic()->physics->CabOccupied) : std::int8_t{0}}; + auto const usercab{uservehicle != blackbox::no_vehicle ? static_cast(train->Dynamic()->physics->CabOccupied()) : std::int8_t{0}}; if (false == m_userknown || uservehicle != m_uservehicle || userincab != m_userincab || usercab != m_usercab) { m_writer->user_vehicle(m_time, uservehicle, userincab, usercab); m_uservehicle = uservehicle; diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index ed6db3738..339b85e00 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -131,7 +131,7 @@ void close_line_breaker(driven const &Driven) { Driven.cab.RelayReset(relay_t::maincircuitground | relay_t::tractionnmotoroverload | relay_t::primaryconverteroverload); if (controlling.EngineType == TEngineType::DieselEngine) { // a mechanical diesel starts at idle, the first position giving the engine fuel - while (controlling.RList[controlling.MainCtrlPos].Mn == 0 && controlling.IncMainCtrl(1)) { + while (controlling.RList[controlling.MainCtrlPos()].Mn == 0 && controlling.IncMainCtrl(1)) { // up to the first position with fuel } } diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index 9f7f78057..4c5ced5ec 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -57,9 +57,9 @@ std::vector traction() { return { {"Mains", [](auto const &M) { return M.lineBreaker.IsClosed() ? 1.0 : 0.0; }}, {"DirActive", [](auto const &M) { return M.DirActive; }}, - {"MainCtrlPos", [](auto const &M) { return M.MainCtrlPos; }}, + {"MainCtrlPos", [](auto const &M) { return M.MainCtrlPos(); }}, {"MainCtrlActualPos", [](auto const &M) { return M.MainCtrlActualPos; }}, - {"ScndCtrlPos", [](auto const &M) { return M.ScndCtrlPos; }}, + {"ScndCtrlPos", [](auto const &M) { return M.ScndCtrlPos(); }}, {"ScndCtrlActualPos", [](auto const &M) { return M.ScndCtrlActualPos; }}, {"Im", [](auto const &M) { return M.Im; }}, {"Itot", [](auto const &M) { return M.Itot; }}, diff --git a/tests/unit/scenario.cpp b/tests/unit/scenario.cpp index 568ade19a..94e58e300 100644 --- a/tests/unit/scenario.cpp +++ b/tests/unit/scenario.cpp @@ -86,7 +86,7 @@ void scenario::full_power(double Seconds) { void scenario::notch_back(int Position) { auto &controlling{driver().controlling}; - while (controlling.MainCtrlPos > Position && controlling.DecMainCtrl(1)) { + while (controlling.MainCtrlPos() > Position && controlling.DecMainCtrl(1)) { wait(1.0); } } diff --git a/tests/unit/test_6dg_power_steps.cpp b/tests/unit/test_6dg_power_steps.cpp index 1df7f30ca..c2ca18274 100644 --- a/tests/unit/test_6dg_power_steps.cpp +++ b/tests/unit/test_6dg_power_steps.cpp @@ -27,17 +27,17 @@ definition shipped() { void move_to(vehicle &Loco, int const Position) { // one notch at a time, as far as the controller goes - while (Loco->MainCtrlPos < Position) { + while (Loco->MainCtrlPos() < Position) { if (false == Loco->IncMainCtrl(1)) { break; } } - while (Loco->MainCtrlPos > Position) { + while (Loco->MainCtrlPos() > Position) { if (false == Loco->DecMainCtrl(1)) { break; } } - REQUIRE(Loco->MainCtrlPos == Position); + REQUIRE(Loco->MainCtrlPos() == Position); } // the 6Dg started up (engine running), its brakes released and its direction set, its controller holding no power diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index a2b5faf5e..e83dcc234 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -70,12 +70,12 @@ TEST_CASE("cab: the engine's idle speed, and the ET42's second controller shown CHECK(et42->GetVirtualScndPos() == 0); et42->brakes.electrodynamic.on = true; CHECK(et42->GetVirtualScndPos() == -1); - et42->ScndCtrlPos = 1; + et42->SetScndCtrlPos(1); CHECK(et42->GetVirtualScndPos() == 1); // with a speed control in place of the second controller, either end of it, for the AI vehicle railbus{definition::fiz("21xm_v1/214ma")}; REQUIRE(railbus->SpeedCtrl); - railbus->ScndCtrlPos = 1; + railbus->SetScndCtrlPos(1); CHECK(railbus->IsScndCtrlNoPowerPos()); CHECK(railbus->IsScndCtrlMaxPowerPos()); CHECK(eu07->IsScndCtrlNoPowerPos()); @@ -259,7 +259,7 @@ TEST_CASE("cab: the SM42's vigilance device switched off in the shunt mode, wher REQUIRE(sm42.CurrentSwitch(true)); REQUIRE(sm42.ShuntMode); scenario.get_going(); - sm42.AnPos = 0.3; + sm42.SetAnPos(0.3); sm42.IncMainCtrl(1); scenario.act("unattended in shunt mode"); bool blinked{false}; @@ -288,7 +288,7 @@ TEST_CASE("cab: the vigilance device of the SM42 kept in the shunt mode, by defa REQUIRE(sm42.CurrentSwitch(true)); REQUIRE(sm42.ShuntMode); scenario.get_going(); - sm42.AnPos = 0.3; + sm42.SetAnPos(0.3); sm42.IncMainCtrl(1); scenario.act("unattended in shunt mode"); CHECK(unattended(scenario, 120)); diff --git a/tests/unit/test_camshaft.cpp b/tests/unit/test_camshaft.cpp index 7231b2c5b..c53cf7490 100644 --- a/tests/unit/test_camshaft.cpp +++ b/tests/unit/test_camshaft.cpp @@ -75,7 +75,7 @@ void running(physics::Vehicle &Locomotive, int const Direction, int const Positi Locomotive.brakes.cylinderPressure = 0.0; Locomotive.lineContactors.Close(); Locomotive.MainCtrlActualPos = Position; - Locomotive.MainCtrlPos = Controller; + Locomotive.SetMainCtrlPos(Controller); Locomotive.lineContactors.RestartSwitchTimer(); Locomotive.lineContactors.AdvanceSwitchTimer(10.0); } @@ -132,6 +132,6 @@ TEST_CASE("camshaft: running forwards, the camshaft goes through all the connect running(physics, 1, 20, 43); CHECK(run_camshaft(physics, 30) == 43); - physics.MainCtrlPos = 10; + physics.SetMainCtrlPos(10); CHECK(run_camshaft(physics, 40) == 10); } diff --git a/tests/unit/test_cntrl.cpp b/tests/unit/test_cntrl.cpp index 394b26d7a..017bc0ee6 100644 --- a/tests/unit/test_cntrl.cpp +++ b/tests/unit/test_cntrl.cpp @@ -53,8 +53,8 @@ int resistance_free_position(physics::Vehicle const &Vehicle, int Position = 0) // the vehicle with its cab occupied, the master controller set to Position and the shunt controller off void controllers_at(vehicle &Vehicle, int Position) { Vehicle->CabActive = 1; - Vehicle->MainCtrlPos = Position; - Vehicle->ScndCtrlPos = 0; + Vehicle->SetMainCtrlPos(Position); + Vehicle->SetScndCtrlPos(0); } } // namespace @@ -77,14 +77,14 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and CHECK(locked->IsScndCtrlLockedByMainCtrl()); CHECK_FALSE(locked->IncScndCtrl(1)); CHECK_FALSE(locked->IncScndCtrl(2)); - CHECK(locked->ScndCtrlPos == 0); + CHECK(locked->ScndCtrlPos() == 0); } SUBCASE("resistive positions") { for (auto position{1}; position < resistancefree; ++position) { CAPTURE(position); controllers_at(locked, position); CHECK_FALSE(locked->IncScndCtrl(1)); - CHECK(locked->ScndCtrlPos == 0); + CHECK(locked->ScndCtrlPos() == 0); } } SUBCASE("every resistance-free position") { @@ -93,7 +93,7 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and controllers_at(locked, position); CHECK_FALSE(locked->IsScndCtrlLockedByMainCtrl()); CHECK(locked->IncScndCtrl(1)); - CHECK(locked->ScndCtrlPos == 1); + CHECK(locked->ScndCtrlPos() == 1); } } SUBCASE("the shunt goes down on a resistance-free position") { @@ -101,18 +101,18 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and REQUIRE(locked->IncScndCtrl(1)); REQUIRE(locked->IncScndCtrl(1)); CHECK(locked->DecScndCtrl(1)); - CHECK(locked->ScndCtrlPos == 1); + CHECK(locked->ScndCtrlPos() == 1); CHECK(locked->DecScndCtrl(2)); - CHECK(locked->ScndCtrlPos == 0); + CHECK(locked->ScndCtrlPos() == 0); } SUBCASE("the shunt doesn't go down on a resistive position either") { // a state the lock doesn't let arise (see below), set by hand to check the controller alone controllers_at(locked, resistancefree - 1); - locked->ScndCtrlPos = 1; + locked->SetScndCtrlPos(1); CHECK(locked->IsScndCtrlLockedByMainCtrl()); CHECK_FALSE(locked->DecScndCtrl(1)); CHECK_FALSE(locked->DecScndCtrl(2)); - CHECK(locked->ScndCtrlPos == 1); + CHECK(locked->ScndCtrlPos() == 1); } SUBCASE("the master controller taken back from a shunt step drops the shunt") { controllers_at(locked, resistancefree); @@ -120,24 +120,24 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and if (locked->TrainType == train_type::et22) { // the ET22's master controller doesn't turn with the shunt on: the shunt goes off first, as before CHECK_FALSE(locked->DecMainCtrl(1)); - CHECK(locked->MainCtrlPos == resistancefree); + CHECK(locked->MainCtrlPos() == resistancefree); CHECK(locked->DecScndCtrl(1)); } CHECK(locked->DecMainCtrl(1)); - CHECK(locked->MainCtrlPos == resistancefree - 1); - CHECK(locked->ScndCtrlPos == 0); + CHECK(locked->MainCtrlPos() == resistancefree - 1); + CHECK(locked->ScndCtrlPos() == 0); // and the master controller goes on down to zero, nothing left locked - while (locked->MainCtrlPos > 0 && locked->DecMainCtrl(1)) { + while (locked->MainCtrlPos() > 0 && locked->DecMainCtrl(1)) { } - CHECK(locked->MainCtrlPos == 0); + CHECK(locked->MainCtrlPos() == 0); } SUBCASE("the master controller set directly (AI, consist) drops the shunt in the next update") { controllers_at(locked, resistancefree); REQUIRE(locked->IncScndCtrl(1)); - locked->MainCtrlPos = resistancefree - 1; + locked->SetMainCtrlPos(resistancefree - 1); locked.step(); - CHECK(locked->ScndCtrlPos == 0); - CHECK(locked->MainCtrlPos == resistancefree - 1); + CHECK(locked->ScndCtrlPos() == 0); + CHECK(locked->MainCtrlPos() == resistancefree - 1); } SUBCASE("the master controller moved up from a shunt step onto a resistive position drops the shunt") { // the last series position, followed by the resistive parallel ones @@ -154,12 +154,12 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and REQUIRE(locked->IncScndCtrl(1)); if (locked->TrainType == train_type::et22) { CHECK_FALSE(locked->IncMainCtrl(1)); // the ET22's interlock, as before - CHECK(locked->ScndCtrlPos == 1); + CHECK(locked->ScndCtrlPos() == 1); } else { CHECK(locked->IncMainCtrl(1)); - CHECK(locked->MainCtrlPos == lastseries + 1); - CHECK(locked->ScndCtrlPos == 0); + CHECK(locked->MainCtrlPos() == lastseries + 1); + CHECK(locked->ScndCtrlPos() == 0); } } } @@ -175,7 +175,7 @@ TEST_CASE("cntrl: without ScndCtrlResistiveLock the field shunting engages on an controllers_at(unlocked, position); CHECK_FALSE(unlocked->IsScndCtrlLockedByMainCtrl()); CHECK(unlocked->IncScndCtrl(1)); - CHECK(unlocked->ScndCtrlPos == 1); + CHECK(unlocked->ScndCtrlPos() == 1); } } } diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index 8566af2f9..e327ac868 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -26,8 +26,8 @@ double flag(bool Value) { // what the commands change std::vector state() { std::vector result{ - {"MainCtrlPos", [](auto const &M) { return M.MainCtrlPos; }}, - {"ScndCtrlPos", [](auto const &M) { return M.ScndCtrlPos; }}, + {"MainCtrlPos", [](auto const &M) { return M.MainCtrlPos(); }}, + {"ScndCtrlPos", [](auto const &M) { return M.ScndCtrlPos(); }}, {"LastRelayTime", [](auto const &M) { return M.lineContactors.TimeSinceSwitch(); }}, {"eimic_real", [](auto const &M) { return M.eimic_real; }}, {"TUHEX_StageActual", [](auto const &M) { return M.TUHEX_StageActual; }}, @@ -65,7 +65,7 @@ std::vector state() { {"MaxCurrentHigh", [](auto const &M) { return flag(M.MotorOverloadRelayHighThreshold); }}, {"Imin", [](auto const &M) { return M.Imin; }}, {"DamageFlag", [](auto const &M) { return M.DamageFlag.Bits(); }}, - {"RadioStop", [](auto const &M) { return flag(M.RadioStopFlag); }}, + {"RadioStop", [](auto const &M) { return flag(M.RadioStopFlag()); }}, {"BrakeDelayFlag", [](auto const &M) { return M.brakes.delaySetting; }}, {"SandDose", [](auto const &M) { return flag(M.SandDose); }}, {"CabSignal", [](auto const &M) { return flag(M.SecuritySystem.is_cabsignal_blinking()); }}, diff --git a/tests/unit/test_consist_braking.cpp b/tests/unit/test_consist_braking.cpp index 1fbb16284..921a636d9 100644 --- a/tests/unit/test_consist_braking.cpp +++ b/tests/unit/test_consist_braking.cpp @@ -57,7 +57,7 @@ constexpr std::size_t demand{2}; // [kN] TEST_CASE("consist braking: the full braking position demands the most deceleration of the consist, over all its mass") { elf unit; REQUIRE(unit.ready); - unit.cab().MainCtrlPos = 0; // the full braking position of the Elf's controller + unit.cab().SetMainCtrlPos(0); // the full braking position of the Elf's controller auto const amax{unit.step(2.0)}; CHECK(amax > 0.0); CHECK(amax <= unit.cab().brakes.blending.maxDeceleration); @@ -75,7 +75,7 @@ TEST_CASE("consist braking: the full braking position demands the most decelerat TEST_CASE("consist braking: standing at full braking, every car brakes with its electropneumatic brake") { elf unit; REQUIRE(unit.ready); - unit.cab().MainCtrlPos = 0; + unit.cab().SetMainCtrlPos(0); unit.step(2.0); for (auto const *car : unit.cars) { CAPTURE(car->Name); @@ -89,7 +89,7 @@ TEST_CASE("consist braking: standing at full braking, every car brakes with its TEST_CASE("consist braking: with the controller at neutral and the train released, moving, nothing is demanded") { elf unit; REQUIRE(unit.ready); - while (unit.cab().MainCtrlPos < unit.cab().MainCtrlNoPowerPos() && unit.cab().IncMainCtrl(1)) { + while (unit.cab().MainCtrlPos() < unit.cab().MainCtrlNoPowerPos() && unit.cab().IncMainCtrl(1)) { // up to neutral } // the controller's demand comes back from full braking to nothing gradually diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp index c191fae53..93b0306b6 100644 --- a/tests/unit/test_crew.cpp +++ b/tests/unit/test_crew.cpp @@ -34,7 +34,7 @@ void get_under_way(consist &Train, int const Position, double const Seconds) { for (int i = 0; i < 90 && false == driver.controlling.lineContactors.IsClosed(); ++i) { test::drive(driver, line, 1.0); } - for (int i = 0; i < 60 && driver.controlling.MainCtrlPos < Position; ++i) { + for (int i = 0; i < 60 && driver.controlling.MainCtrlPos() < Position; ++i) { driver.controlling.IncMainCtrl(1); test::drive(driver, line, 1.0); } @@ -193,16 +193,16 @@ TEST_CASE("crew: a locomotive under power left by its driver stops and stays bra get_under_way(train, 20, 30.0); auto &eu07{train[0].physics()}; REQUIRE(train[0].speed() > 20.0); - REQUIRE(eu07.MainCtrlPos > 0); + REQUIRE(eu07.MainCtrlPos() > 0); REQUIRE(eu07.lineBreaker.IsClosed()); crew::secure(eu07, eu07); - CHECK(eu07.MainCtrlPos == eu07.MainCtrlNoPowerPos()); - CHECK(eu07.ScndCtrlPos == 0); + CHECK(eu07.MainCtrlPos() == eu07.MainCtrlNoPowerPos()); + CHECK(eu07.ScndCtrlPos() == 0); CHECK(eu07.brakes.handlePosition == static_cast(eu07.brakes.driverValve->GetPos(bh_EB))); CHECK(eu07.CabActive == 0); - CHECK(eu07.CabOccupied == 0); + CHECK(eu07.CabOccupied() == 0); CHECK_FALSE(eu07.CabMaster); auto const stoppedafter{seconds_to_stop(train, 120.0)}; @@ -221,7 +221,7 @@ 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->SetWarningSignal(1); cab->signal_departure(true); cab->Sandbox(true); REQUIRE(cab->DepartureSignal); @@ -229,7 +229,7 @@ TEST_CASE("crew: what the AI held is let go when the driver leaves") { crew::secure(cab.physics(), cab.physics()); - CHECK(cab->WarningSignal == 0); + CHECK(cab->WarningSignal() == 0); CHECK_FALSE(cab->DepartureSignal); CHECK_FALSE(cab->SandDose); } @@ -284,17 +284,17 @@ TEST_CASE("crew: the power an integrated handle asked for goes when the driver l // 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->SetMainCtrlPos(impuls->MainCtrlPosNo); impuls->eimic = 0.8; impuls->eimic_real = 0.8; crew::secure(impuls.physics(), impuls.physics()); - CHECK(impuls->MainCtrlPos == impuls->MainCtrlNoPowerPos()); + CHECK(impuls->MainCtrlPos() == impuls->MainCtrlNoPowerPos()); CHECK(impuls->eimic == 0.0); CHECK(impuls->eimic_real == 0.0); CHECK(impuls->brakes.handlePosition == static_cast(impuls->brakes.driverValve->GetPos(bh_EB))); - CHECK(impuls->CabOccupied == 0); + CHECK(impuls->CabOccupied() == 0); } TEST_CASE("crew: a road vehicle left by its driver gets the brake the driver stops it with") { @@ -307,7 +307,7 @@ TEST_CASE("crew: a road vehicle left by its driver gets the brake the driver sto crew::secure(bus.physics(), bus.physics()); CHECK(bus->brakes.independentPosition == 1.0); - CHECK(bus->MainCtrlPos == bus->MainCtrlNoPowerPos()); + 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_definition.cpp b/tests/unit/test_definition.cpp index 0abcc824a..eeffd49e0 100644 --- a/tests/unit/test_definition.cpp +++ b/tests/unit/test_definition.cpp @@ -41,7 +41,7 @@ TEST_CASE("definition: rows of a table section reach the vehicle") { .set("LightsList", "rows", {{0, 0}, {pc1, 0}})}; CHECK(wagon->LightsPosNo == 2); - CHECK(wagon->LightsPos == 1); + CHECK(wagon->LightsPos() == 1); CHECK(wagon->Lights[VehicleEnd::front][1] == pc1); } diff --git a/tests/unit/test_diesel.cpp b/tests/unit/test_diesel.cpp index b2713b620..5328c439b 100644 --- a/tests/unit/test_diesel.cpp +++ b/tests/unit/test_diesel.cpp @@ -92,7 +92,7 @@ TEST_CASE("diesel: the 214M railbus's torque converter, gears and retarder") { auto &railbus{scenario.cab()}; scenario.get_going(); scenario.full_power(60.0); - CHECK(railbus.MainCtrlPos == 5); + CHECK(railbus.MainCtrlPos() == 5); CHECK(railbus.eimic_real == doctest::Approx(1.0)); CHECK(railbus.torqueConverter.lockedUp); CHECK(railbus.ScndCtrlActualPos == railbus.ScndCtrlPosNo); @@ -101,7 +101,7 @@ TEST_CASE("diesel: the 214M railbus's torque converter, gears and retarder") { bool retarder; bool air; }; - auto number{railbus.MainCtrlPos}; + auto number{railbus.MainCtrlPos()}; for (auto const &[eimic, retarder, air] : {position{1.0, false, false}, position{0.0, false, false}, position{-1.0, true, false}, position{0.0, false, true}}) { --number; CAPTURE(number); @@ -193,7 +193,7 @@ TEST_CASE("diesel: the SM42's shunt mode, switched on and off with one move of t CHECK(sm42.ShuntMode); scenario.get_going(); scenario.act("shunting power"); - sm42.AnPos = 0.5; + sm42.SetAnPos(0.5); CHECK(sm42.IncMainCtrl(1)); scenario.wait(60.0); CHECK(sm42.Vel > 1.0); diff --git a/tests/unit/test_dimmer.cpp b/tests/unit/test_dimmer.cpp index d4d2e2663..2368b7ff6 100644 --- a/tests/unit/test_dimmer.cpp +++ b/tests/unit/test_dimmer.cpp @@ -31,15 +31,15 @@ TEST_CASE("dimmer: a position outside the list reads as a plain one, neither off for (auto const position : {-1, 2, 100}) { CAPTURE(position); - cab->modernDimmerPosition = position; + cab->SetDimmerPosition(position); auto const entry{cab->currentDimPosition()}; CHECK_FALSE(entry.isOff); CHECK_FALSE(entry.isDimmed); CHECK_FALSE(entry.isHighBeam); } - cab->modernDimmerPosition = 0; + cab->SetDimmerPosition(0); CHECK(cab->currentDimPosition().isOff); - cab->modernDimmerPosition = 1; + cab->SetDimmerPosition(1); CHECK(cab->currentDimPosition().isDimmed); } @@ -57,7 +57,7 @@ TEST_CASE("dimmer: a DefaultPos past the end of the list starts the dimmer at it CHECK(cab->modernDimmerDefaultPosition == 1); // the cab puts the modern dimmer to its default position when it's entered (TTrain::set_cab_controls()) - cab->modernDimmerPosition = cab->modernDimmerDefaultPosition; + cab->SetDimmerPosition(cab->modernDimmerDefaultPosition); CHECK(cab->currentDimPosition().isDimmed); } @@ -65,7 +65,7 @@ TEST_CASE("dimmer: without the modern dimmer a DefaultPos past the end of the li vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed}), 7).set("Switches", "ModernDimmer", "No")}; REQUIRE_FALSE(cab->enableModernDimmer); - CHECK(cab->modernDimmerPosition == 1); + CHECK(cab->DimmerPosition() == 1); CHECK(cab->currentDimPosition().isDimmed); } @@ -74,39 +74,39 @@ TEST_CASE("dimmer: an empty list leaves the dimmer at 0, reading as a plain posi REQUIRE(cab->dimPositions.empty()); CHECK(cab->modernDimmerDefaultPosition == 0); - CHECK(cab->modernDimmerPosition == 0); + CHECK(cab->DimmerPosition() == 0); CHECK(cab->clampDimmerPosition(1) == 0); CHECK_FALSE(cab->currentDimPosition().isOff); CHECK_FALSE(cab->stepDimmerPosition(1)); CHECK_FALSE(cab->stepDimmerPosition(-1)); - CHECK(cab->modernDimmerPosition == 0); + CHECK(cab->DimmerPosition() == 0); } TEST_CASE("dimmer: stepping stays within the list") { SUBCASE("without cycling it stops at the ends") { vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed, off}), 0)}; CHECK_FALSE(cab->stepDimmerPosition(-1)); - CHECK(cab->modernDimmerPosition == 0); + CHECK(cab->DimmerPosition() == 0); CHECK(cab->stepDimmerPosition(1)); CHECK(cab->stepDimmerPosition(1)); - CHECK(cab->modernDimmerPosition == 2); + CHECK(cab->DimmerPosition() == 2); CHECK_FALSE(cab->stepDimmerPosition(1)); - CHECK(cab->modernDimmerPosition == 2); + CHECK(cab->DimmerPosition() == 2); } SUBCASE("with cycling it goes around to the other end") { vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed, off}), 0, true)}; CHECK(cab->stepDimmerPosition(-1)); - CHECK(cab->modernDimmerPosition == 2); + CHECK(cab->DimmerPosition() == 2); CHECK(cab->stepDimmerPosition(1)); - CHECK(cab->modernDimmerPosition == 0); + CHECK(cab->DimmerPosition() == 0); } SUBCASE("a position past the end steps from the last one") { vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed, off}), 0)}; - cab->modernDimmerPosition = 9; + cab->SetDimmerPosition(9); CHECK(cab->stepDimmerPosition(-1)); - CHECK(cab->modernDimmerPosition == 1); - cab->modernDimmerPosition = 9; + CHECK(cab->DimmerPosition() == 1); + cab->SetDimmerPosition(9); CHECK(cab->stepDimmerPosition(1)); // can't go further, but comes back into the list - CHECK(cab->modernDimmerPosition == 2); + CHECK(cab->DimmerPosition() == 2); } } diff --git a/tests/unit/test_drivingaid.cpp b/tests/unit/test_drivingaid.cpp index b12c80851..6b609b8ad 100644 --- a/tests/unit/test_drivingaid.cpp +++ b/tests/unit/test_drivingaid.cpp @@ -33,8 +33,8 @@ drivingaid::readout read(vehicle &Vehicle, drivingaid::cab_controls const &Cab) // what the panel showed before: the throttle and brakes numbers, and the local brake always drivingaid::readout before(physics::Vehicle const &Physics) { drivingaid::readout result; - result.throttle_first = Physics.EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * Physics.eimic_real)) : Physics.MainCtrlPos; - result.throttle_second = Physics.EIMCtrlType > 0 ? Physics.MainCtrlPos : Physics.ScndCtrlPos; + result.throttle_first = Physics.EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * Physics.eimic_real)) : Physics.MainCtrlPos(); + result.throttle_second = Physics.EIMCtrlType > 0 ? Physics.MainCtrlPos() : Physics.ScndCtrlPos(); result.brake_first = Physics.UniCtrlIntegratedBrakeCtrl ? std::max(0.0, -100.0 * Physics.eimic_real) : Physics.brakes.handlePositionSmooth; result.local_brake = Physics.brakes.independentPosition * LocalBrakePosNo; return result; @@ -52,7 +52,7 @@ TEST_CASE("driving aid: the Vectron's ED lever shows as a negative throttle step // 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(idle.throttle_first == vectron->MainCtrlPos()); CHECK_FALSE(idle.ed_percent.has_value()); CHECK(idle.show_local_brake); @@ -83,7 +83,7 @@ TEST_CASE("driving aid: the Traxx's ED braking from its master controller") { CHECK_FALSE(read(traxx, lever_cab).ed_percent.has_value()); // B+: the braking demand ramps towards full - traxx->MainCtrlPos = 0; + traxx->SetMainCtrlPos(0); traxx.run(3.0, line); REQUIRE(traxx->eimic_real < -0.2); auto const braking{read(traxx, lever_cab)}; @@ -106,7 +106,7 @@ TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, CHECK_FALSE(idle.ed_percent.has_value()); // the controller at its lowest braking position: the demand ramps towards full braking - elf->MainCtrlPos = 0; + elf->SetMainCtrlPos(0); elf.run(2.0, line); REQUIRE(elf->eimic_real < -0.1); auto const braking{read(elf, elf_cab)}; @@ -125,11 +125,11 @@ TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, 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->SetMainCtrlPos(5); eu07->brakes.independentPosition = 0.2; auto const readout{read(eu07, lever_cab)}; CHECK(readout.throttle_first == 5); - CHECK(readout.throttle_second == eu07->ScndCtrlPos); + 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()); @@ -161,7 +161,7 @@ TEST_CASE("driving aid: every real vehicle with a local brake control shows the 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->SetMainCtrlPos(std::min(mainctrl, real->MainCtrlPosNo)); real->brakes.independentPosition = localbrake; real->eimic_real = eimic; auto const now{read(real, lever_cab)}; diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp index 0f7f084de..9658f4123 100644 --- a/tests/unit/test_dynamic_brake_diesel.cpp +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -60,8 +60,8 @@ double st44_limit(physics::Vehicle const &Vehicle) { // the controller of the BR285 down to the given position, a step a time void controller_to(physics::Vehicle &Locomotive, int Position) { - while (Locomotive.MainCtrlPos > Position && Locomotive.DecMainCtrl(1)) {} - while (Locomotive.MainCtrlPos < Position && Locomotive.IncMainCtrl(1)) {} + while (Locomotive.MainCtrlPos() > Position && Locomotive.DecMainCtrl(1)) {} + while (Locomotive.MainCtrlPos() < Position && Locomotive.IncMainCtrl(1)) {} } } // namespace diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index 7f11594f1..e1fa8df1e 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -56,7 +56,7 @@ struct elf { for (int i = 0; i < 3 && cab().DirActive <= 0; ++i) { cab().DirectionForward(); } - while (cab().MainCtrlPos < cab().MainCtrlNoPowerPos() && cab().IncMainCtrl(1)) { + while (cab().MainCtrlPos() < cab().MainCtrlNoPowerPos() && cab().IncMainCtrl(1)) { // up to neutral } test::release_brakes(cab()); @@ -76,9 +76,9 @@ struct elf { physics::Vehicle &car(std::size_t Index) { return unit[Index].physics(); } // the driver moves the controller notch by notch, which the cab sends on to the coupled vehicles void set_controller(int Position) { - while (cab().MainCtrlPos < Position && cab().IncMainCtrl(1)) { + while (cab().MainCtrlPos() < Position && cab().IncMainCtrl(1)) { } - while (cab().MainCtrlPos > Position && cab().DecMainCtrl(1)) { + while (cab().MainCtrlPos() > Position && cab().DecMainCtrl(1)) { } } void wait(double Seconds) { test::drive(test::driving(unit), line, Seconds); } @@ -99,9 +99,9 @@ TEST_CASE("elf controller: without EIMCtrlMainEmergency the positions stay as th CHECK(physics.EIMCtrlEmergencyPositions() == 0); CHECK(physics.MainCtrlPosNo == 4); CHECK(physics.MainCtrlNoPowerPos() == 3); - CHECK(physics.MainCtrlPos == 3); + CHECK(physics.MainCtrlPos() == 3); // the lowest position brakes fully, without emptying the pipe - physics.MainCtrlPos = 0; + physics.SetMainCtrlPos(0); CHECK_FALSE(physics.IsMainCtrlEmergencyPos()); unit.wait(10.0); CHECK(physics.eimic == doctest::Approx(-1.0)); @@ -117,27 +117,27 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency shifts the positions up by the e CHECK(physics.EIMCtrlEmergencyPositions() == 1); CHECK(physics.MainCtrlPosNo == 5); CHECK(physics.MainCtrlNoPowerPos() == 4); - CHECK(physics.MainCtrlPos == 4); + CHECK(physics.MainCtrlPos() == 4); CHECK_FALSE(physics.IsMainCtrlEmergencyPos()); SUBCASE("the neutral position neither drives nor brakes") { unit.wait(5.0); CHECK(physics.eimic == doctest::Approx(0.0)); } SUBCASE("the full braking position, formerly 0, brakes fully without emptying the pipe") { - physics.MainCtrlPos = 1; + physics.SetMainCtrlPos(1); unit.wait(10.0); CHECK(physics.eimic == doctest::Approx(-1.0)); CHECK(physics.brakePipe.Pressure() > 4.5); } SUBCASE("the braking position, formerly 1, ramps the braking up") { - physics.MainCtrlPos = 2; + physics.SetMainCtrlPos(2); unit.wait(1.0); CHECK(physics.eimic < 0.0); CHECK(physics.eimic > -1.0); CHECK(physics.brakePipe.Pressure() > 4.5); } SUBCASE("the emergency brake position brakes fully at once and empties the pipe") { - physics.MainCtrlPos = 0; + physics.SetMainCtrlPos(0); CHECK(physics.IsMainCtrlEmergencyPos()); // a single step of the physics unit.unit.step(unit.line); @@ -146,7 +146,7 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency shifts the positions up by the e CHECK(physics.brakePipe.Pressure() < 0.5); CHECK(physics.brakes.cylinderPressure > 1.0); // out of it the pipe charges again - physics.MainCtrlPos = physics.MainCtrlNoPowerPos(); + physics.SetMainCtrlPos(physics.MainCtrlNoPowerPos()); CHECK_FALSE(physics.IsMainCtrlEmergencyPos()); unit.recharge(); CHECK(physics.brakePipe.Pressure() > 4.5); @@ -172,7 +172,7 @@ TEST_CASE("elf controller: the reverser works at the neutral shifted by EIMCtrlM elf unit{{data::emergency_old_layout}}; REQUIRE(unit.ready); auto &physics{unit.cab()}; - REQUIRE(physics.MainCtrlPos == physics.MainCtrlNoPowerPos()); + REQUIRE(physics.MainCtrlPos() == physics.MainCtrlNoPowerPos()); REQUIRE(physics.DirActive == 1); CHECK(physics.DirectionBackward()); CHECK(physics.DirActive == 0); @@ -180,7 +180,7 @@ TEST_CASE("elf controller: the reverser works at the neutral shifted by EIMCtrlM CHECK(physics.DirActive == 1); // not in the power position unit.set_controller(physics.MainCtrlNoPowerPos() + 1); - REQUIRE(physics.MainCtrlPos == 5); + REQUIRE(physics.MainCtrlPos() == 5); CHECK_FALSE(physics.DirectionBackward()); CHECK(physics.DirActive == 1); } @@ -191,7 +191,7 @@ TEST_CASE("elf controller: the emergency brake position vents the pipe only from REQUIRE(unit.charged); // the rear car, with its own cab, has its controller in the emergency brake position, the driven one not auto &rear{unit.car(2)}; - rear.MainCtrlPos = 0; + rear.SetMainCtrlPos(0); CHECK(rear.IsMainCtrlEmergencyPos()); CHECK_FALSE(rear.IsCabMaster()); unit.wait(10.0); @@ -207,22 +207,22 @@ TEST_CASE("elf controller: an Elf with the emergency brake position leading one auto &other{unit.car(3)}; REQUIRE_FALSE(other.EIMCtrlMainEmergency); // neutral of the lead is neutral of the other - CHECK(lead.MainCtrlPos == 4); - CHECK(other.MainCtrlPos == other.MainCtrlNoPowerPos()); + CHECK(lead.MainCtrlPos() == 4); + CHECK(other.MainCtrlPos() == other.MainCtrlNoPowerPos()); SUBCASE("power") { unit.set_controller(5); - CHECK(other.MainCtrlPos == 4); + CHECK(other.MainCtrlPos() == 4); } SUBCASE("full braking") { unit.set_controller(1); - CHECK(other.MainCtrlPos == 0); + CHECK(other.MainCtrlPos() == 0); unit.wait(10.0); CHECK(lead.brakePipe.Pressure() > 4.5); } SUBCASE("the emergency brake: the other one at its full braking, the pipe vented by the lead") { unit.set_controller(0); REQUIRE(lead.IsMainCtrlEmergencyPos()); - CHECK(other.MainCtrlPos == 0); + CHECK(other.MainCtrlPos() == 0); unit.wait(10.0); CHECK(lead.brakePipe.Pressure() < 0.5); CHECK(other.brakePipe.Pressure() < 0.5); @@ -236,15 +236,15 @@ TEST_CASE("elf controller: an Elf without the emergency brake position leading o auto &lead{unit.cab()}; auto &other{unit.car(3)}; REQUIRE(other.EIMCtrlMainEmergency); - CHECK(lead.MainCtrlPos == 3); - CHECK(other.MainCtrlPos == other.MainCtrlNoPowerPos()); + CHECK(lead.MainCtrlPos() == 3); + CHECK(other.MainCtrlPos() == other.MainCtrlNoPowerPos()); SUBCASE("power") { unit.set_controller(4); - CHECK(other.MainCtrlPos == 5); + CHECK(other.MainCtrlPos() == 5); } SUBCASE("the full braking of the lead is the full braking of the other, not its emergency brake") { unit.set_controller(0); - CHECK(other.MainCtrlPos == 1); + CHECK(other.MainCtrlPos() == 1); CHECK_FALSE(other.IsMainCtrlEmergencyPos()); unit.wait(10.0); CHECK(lead.brakePipe.Pressure() > 4.5); @@ -257,7 +257,7 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency leaves the other controllers alo vehicle impuls{definition::fiz("impuls_v1/31we-a_pr").set("Cntrl", "EIMCtrlMainEmergency", "Yes"), 60.0, "impuls", 1}; CHECK(impuls->EIMCtrlEmergencyPositions() == 0); CHECK(impuls->MainCtrlPosNo == 10); - impuls->MainCtrlPos = 0; + impuls->SetMainCtrlPos(0); CHECK_FALSE(impuls->IsMainCtrlEmergencyPos()); } diff --git a/tests/unit/test_engine_shutdown.cpp b/tests/unit/test_engine_shutdown.cpp index a841da08d..e5ccbec74 100644 --- a/tests/unit/test_engine_shutdown.cpp +++ b/tests/unit/test_engine_shutdown.cpp @@ -11,7 +11,7 @@ namespace { // the shunter with its engine started from the cab and idling test::vehicle running_shunter() { test::vehicle shunter{test::definition::load("diesel_shunter")}; - shunter->CabOccupied = 1; + shunter->SetCabOccupied(1); shunter->CabActivisation(); shunter->BatterySwitch(true); shunter->OilPumpSwitch(true); diff --git a/tests/unit/test_engine_start.cpp b/tests/unit/test_engine_start.cpp index 1f7e1c684..b58f0cf77 100644 --- a/tests/unit/test_engine_start.cpp +++ b/tests/unit/test_engine_start.cpp @@ -32,7 +32,7 @@ void prepare(consist &Train) { cab.CabActivisation(); cab.OilPumpSwitch(true); cab.FuelPumpSwitch(true); - while (cab.RList[cab.MainCtrlPos].R == 0.0 && cab.IncMainCtrl(1)) { + while (cab.RList[cab.MainCtrlPos()].R == 0.0 && cab.IncMainCtrl(1)) { // up to the first position with fuel } Train.run(20.0); @@ -82,14 +82,14 @@ TEST_CASE("engine start: the vehicles in multiple, counted from the cab's own on CHECK(engine_start::engine(first, first, 4) == nullptr); CHECK(engine_start::engine(first, first, 0) == nullptr); // from the rear cab of the first railcar the others are in front of the cab, in the same order - first.CabOccupied = -1; + first.SetCabOccupied(-1); CHECK(engine_start::engine(first, first, 2) == &second); CHECK(engine_start::engine(first, first, 3) == &third); // from the middle one, the one behind its cab comes first - second.CabOccupied = 1; + second.SetCabOccupied(1); CHECK(engine_start::engine(second, second, 2) == &third); CHECK(engine_start::engine(second, second, 3) == &first); - second.CabOccupied = -1; + second.SetCabOccupied(-1); CHECK(engine_start::engine(second, second, 2) == &first); CHECK(engine_start::engine(second, second, 3) == &third); } @@ -103,7 +103,7 @@ TEST_CASE("engine start: only the vehicles with an engine and under control thro REQUIRE(trailer.Power < 0.01); CHECK(engine_start::engine(first, first, 2) == &second); // the vehicle with the cab doesn't drive itself: its engine is in the vehicle it controls, which isn't counted twice - trailer.CabOccupied = 1; + trailer.SetCabOccupied(1); CHECK(engine_start::engine(trailer, first, 1) == &first); CHECK(engine_start::engine(trailer, first, 2) == &second); CHECK(engine_start::engine(trailer, first, 3) == nullptr); diff --git a/tests/unit/test_field_shunting.cpp b/tests/unit/test_field_shunting.cpp index e761e59d7..ac44a4fdc 100644 --- a/tests/unit/test_field_shunting.cpp +++ b/tests/unit/test_field_shunting.cpp @@ -56,20 +56,20 @@ TEST_CASE("field shunting: the SU45 with its switch, off at full power and switc scenario.full_power(120.0); CHECK(su45.IsMainCtrlMaxPowerPos()); CHECK(su45.lineContactors.IsClosed()); - CHECK(su45.ScndCtrlPos == 0); + CHECK(su45.ScndCtrlPos() == 0); CHECK_FALSE(su45.IncScndCtrl(1)); scenario.wait(1.0); - CHECK(su45.ScndCtrlPos == 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); + 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); + CHECK(su45.ScndCtrlPos() == 0); scenario.check(); } @@ -90,10 +90,10 @@ TEST_CASE("field shunting: a diesel-electric with AutoRelay=Optional alone shunt CHECK(su45.lineContactors.IsClosed()); // over 50 km/h: the relays don't shunt, the driver does CHECK(su45.Vel > 50.0); - CHECK(su45.ScndCtrlPos == 0); + CHECK(su45.ScndCtrlPos() == 0); scenario.act("field shunting by hand"); CHECK(su45.IncScndCtrl(1)); scenario.wait(1.0); - CHECK(su45.ScndCtrlPos == 1); + CHECK(su45.ScndCtrlPos() == 1); scenario.check(); } diff --git a/tests/unit/test_gauge_scale.cpp b/tests/unit/test_gauge_scale.cpp index 9e59e5114..2e4d7ddd6 100644 --- a/tests/unit/test_gauge_scale.cpp +++ b/tests/unit/test_gauge_scale.cpp @@ -87,7 +87,7 @@ TEST_CASE("main ctrl act: the marker of a diesel locomotive with a scaletable: f auto &locomotive{train.add(definition::fiz(path), 1).physics()}; REQUIRE((locomotive.EngineType == TEngineType::DieselElectric || locomotive.EngineType == TEngineType::DieselEngine)); REQUIRE(locomotive.EIMCtrlType == 0); - locomotive.MainCtrlPos = 5; + locomotive.SetMainCtrlPos(5); CHECK(locomotive.MainCtrlActualPos == 0); CHECK(main_ctrl_act::position(locomotive, true) == doctest::Approx(5.0)); // one with a controller of the EIM kind keeps its actual position itself @@ -103,8 +103,8 @@ TEST_CASE("main ctrl act: the marker of a diesel locomotive without a scaletable consist train; auto &locomotive{train.add(definition::fiz(path), 1).physics()}; REQUIRE(locomotive.EIMCtrlType == 0); - locomotive.MainCtrlPos = 5; - locomotive.ScndCtrlPos = 1; + locomotive.SetMainCtrlPos(5); + locomotive.SetScndCtrlPos(1); for (auto const coupled : {false, true}) { CAPTURE(coupled); locomotive.CoupledCtrl = coupled; @@ -118,9 +118,9 @@ TEST_CASE("main ctrl act: the marker of an electric locomotive shows its actual CAPTURE(scaletable); consist train; auto &locomotive{train.add(definition::fiz("et22_v3/201e-w"), 1).physics()}; - locomotive.MainCtrlPos = 10; + locomotive.SetMainCtrlPos(10); locomotive.MainCtrlActualPos = 3; - locomotive.ScndCtrlPos = 2; + locomotive.SetScndCtrlPos(2); locomotive.ScndCtrlActualPos = 1; locomotive.CoupledCtrl = false; CHECK(main_ctrl_act::position(locomotive, scaletable) == doctest::Approx(3.0)); diff --git a/tests/unit/test_handover.cpp b/tests/unit/test_handover.cpp index 03dc4d8c2..dd5ed15ae 100644 --- a/tests/unit/test_handover.cpp +++ b/tests/unit/test_handover.cpp @@ -25,14 +25,14 @@ vehicle cab_vehicle() { TEST_CASE("handover: the horn the AI was sounding goes quiet (eu07/maszyna#511)") { auto cab{cab_vehicle()}; - SUBCASE("low tone") { cab->WarningSignal = 1; } - SUBCASE("high tone") { cab->WarningSignal = 2; } - SUBCASE("both tones") { cab->WarningSignal = 1 | 2; } - REQUIRE(cab->WarningSignal != 0); + SUBCASE("low tone") { cab->SetWarningSignal(1); } + SUBCASE("high tone") { cab->SetWarningSignal(2); } + SUBCASE("both tones") { cab->SetWarningSignal(1 | 2); } + REQUIRE(cab->WarningSignal() != 0); handover::release_ai_controls(cab.physics(), cab.physics()); - CHECK(cab->WarningSignal == 0); + CHECK(cab->WarningSignal() == 0); } TEST_CASE("handover: sanding the AI started stops") { @@ -84,7 +84,7 @@ TEST_CASE("handover: nothing the AI didn't latch changes") { handover::release_ai_controls(cab.physics(), cab.physics()); - CHECK(cab->WarningSignal == 0); + CHECK(cab->WarningSignal() == 0); CHECK_FALSE(cab->SandDose); CHECK_FALSE(cab->DepartureSignal); CHECK_FALSE(cab->brakes.distributor->Releaser()); @@ -92,7 +92,7 @@ TEST_CASE("handover: nothing the AI didn't latch changes") { TEST_CASE("handover: the light selector moves to the position giving the head lights the AI has set") { auto cab{cab_vehicle()}; - REQUIRE(cab->LightsPos == 1); // untouched selector: lights off + REQUIRE(cab->LightsPos() == 1); // untouched selector: lights off SUBCASE("Pc1") { CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), pc1, allheadlights) == 2); @@ -129,7 +129,7 @@ TEST_CASE("handover: the light selector stays within its table") { TEST_CASE("handover: the light selector already matching the lights stays") { auto cab{cab_vehicle()}; - cab->LightsPos = 2; // Pc1 + cab->SetLightsPos(2); // Pc1 CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), pc1, allheadlights) == 2); } @@ -138,7 +138,7 @@ TEST_CASE("handover: the headlight dimmer leaves the off position when the head auto cab{cab_vehicle()}; REQUIRE(cab->enableModernDimmer); REQUIRE(cab->dimPositions.size() == 5); - cab->modernDimmerPosition = 2; // off, left there by the player before the AI took over + cab->SetDimmerPosition(2); // off, left there by the player before the AI took over SUBCASE("to the default position") { CHECK(handover::dimmer_position(cab.physics(), true) == 3); @@ -156,7 +156,7 @@ TEST_CASE("handover: the headlight dimmer in any other position stays") { auto cab{cab_vehicle()}; for (auto const position : {0, 1, 3, 4}) { CAPTURE(position); - cab->modernDimmerPosition = position; + cab->SetDimmerPosition(position); CHECK(handover::dimmer_position(cab.physics(), true) == position); } } @@ -165,5 +165,5 @@ TEST_CASE("handover: a vehicle without the modern dimmer keeps its dimmer state" vehicle wagon{definition::load("wagon")}; REQUIRE_FALSE(wagon->enableModernDimmer); - CHECK(handover::dimmer_position(wagon.physics(), true) == wagon->modernDimmerPosition); + CHECK(handover::dimmer_position(wagon.physics(), true) == wagon->DimmerPosition()); } diff --git a/tests/unit/test_line_contactors.cpp b/tests/unit/test_line_contactors.cpp index f332b4432..1f8e8551b 100644 --- a/tests/unit/test_line_contactors.cpp +++ b/tests/unit/test_line_contactors.cpp @@ -66,7 +66,7 @@ namespace { // the diesel-electric locomotive with its engine running and the brakes released, the master controller at 0 test::vehicle diesel_electric() { test::vehicle vehicle{test::definition::load("diesel_electric")}; - vehicle->CabOccupied = 1; + vehicle->SetCabOccupied(1); vehicle->CabActivisation(); vehicle->BatterySwitch(true); vehicle->OilPumpSwitch(true); diff --git a/tests/unit/test_mains_before_pantographs.cpp b/tests/unit/test_mains_before_pantographs.cpp index ea615d1f5..99e79ec65 100644 --- a/tests/unit/test_mains_before_pantographs.cpp +++ b/tests/unit/test_mains_before_pantographs.cpp @@ -77,7 +77,7 @@ void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const test::drive(Driven, line, 1.0); } test::drive(Driven, line, 2.0); - REQUIRE(Loco->MainCtrlPos == Position); + REQUIRE(Loco->MainCtrlPos() == Position); REQUIRE(Loco->MainCtrlActualPos == Position); REQUIRE(Loco->RList[Position].R > 0.0); // a resistance position REQUIRE(Loco->lineContactors.IsClosed()); @@ -223,7 +223,7 @@ TEST_CASE("mains before pantographs: with the flag whatever else the main circui REQUIRE(loco->lineBreaker.IsClosed()); loco->CompressorSwitch(true); loco->MotorBlowersSwitch(true, VehicleEnd::front); - loco->RVentForceOn = true; + loco->SetRVentForceOn(true); loco->HeatingSwitch(true); loco.hold_main_reservoir(-1.0); @@ -297,7 +297,7 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when // there, the motors still cut off; the converter is back on its own test::drive(driven, line, 10.0); REQUIRE(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); - REQUIRE(loco->MainCtrlPos == 5); + REQUIRE(loco->MainCtrlPos() == 5); CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->converter.IsRunning()); CHECK_FALSE(loco->protection.UndervoltageHolds()); @@ -306,10 +306,10 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when CHECK(loco->Im == 0.0); SUBCASE("the master controller back at zero: the start goes as usual") { - while (loco->MainCtrlPos > 0 && loco->DecMainCtrl(1)) { + while (loco->MainCtrlPos() > 0 && loco->DecMainCtrl(1)) { // down to zero } - REQUIRE(loco->MainCtrlPos == 0); + REQUIRE(loco->MainCtrlPos() == 0); test::drive(driven, line, 1.0); CHECK(loco->protection.UndervoltageHolds()); CHECK_FALSE(loco->lineContactors.IsClosed()); @@ -322,10 +322,10 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when CHECK(std::abs(loco->Im) > 10.0); } SUBCASE("the master controller back at the first position, where the line contactors close on a start") { - while (loco->MainCtrlPos > 1 && loco->DecMainCtrl(1)) { + while (loco->MainCtrlPos() > 1 && loco->DecMainCtrl(1)) { // down to the first position } - REQUIRE(loco->MainCtrlPos == 1); + REQUIRE(loco->MainCtrlPos() == 1); test::drive(driven, line, 2.0); CHECK(loco->protection.UndervoltageHolds()); CHECK(loco->lineContactors.IsClosed()); diff --git a/tests/unit/test_pressure_switch.cpp b/tests/unit/test_pressure_switch.cpp index 1fe1c76fb..1a50a0931 100644 --- a/tests/unit/test_pressure_switch.cpp +++ b/tests/unit/test_pressure_switch.cpp @@ -55,11 +55,11 @@ void get_ready(test::vehicle &Loco, test::driven const &Driven) { // 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)) { + while (Loco->MainCtrlPos() < Position && Loco->IncMainCtrl(1)) { test::drive(Driven, line, 1.0); } test::drive(Driven, line, 2.0); - REQUIRE(Loco->MainCtrlPos == Position); + REQUIRE(Loco->MainCtrlPos() == Position); } void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const Position) { @@ -165,7 +165,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller } test::drive(driven, line, 10.0); REQUIRE(loco->brakePipe.Pressure() < emergency_pressure); - REQUIRE(loco->MainCtrlPos == 5); + REQUIRE(loco->MainCtrlPos() == 5); CHECK_FALSE(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->pantographs[VehicleEnd::front].is_active); CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); @@ -188,7 +188,7 @@ TEST_CASE("pressure switch: an emergency application with the master controller // down to zero } test::drive(driven, line, 2.0); - REQUIRE(loco->MainCtrlPos == 0); + REQUIRE(loco->MainCtrlPos() == 0); emergency_application(loco, driven); CHECK(loco->lineBreaker.IsClosed()); @@ -231,7 +231,7 @@ TEST_CASE("pressure switch: without the key an emergency application leaves the get_under_power(loco, driven, 5); emergency_application(loco, driven); - REQUIRE(loco->MainCtrlPos == 5); + REQUIRE(loco->MainCtrlPos() == 5); CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); @@ -269,7 +269,7 @@ TEST_CASE("pressure switch: after the emergency application the driver's start-u // with the brake pipe still empty REQUIRE(test::start_up(driven, line, 60.0)); - CHECK(loco->MainCtrlPos == 0); + CHECK(loco->MainCtrlPos() == 0); CHECK(loco->lineBreaker.IsClosed()); CHECK(loco->pantographs[VehicleEnd::rear].is_active); CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); diff --git a/tests/unit/test_radio.cpp b/tests/unit/test_radio.cpp index 696624cce..45e86d540 100644 --- a/tests/unit/test_radio.cpp +++ b/tests/unit/test_radio.cpp @@ -7,7 +7,7 @@ TEST_CASE("radio: a radio switched on with the low voltage works") { test::vehicle vehicle{test::definition::load("wagon")}; - vehicle->Radio = true; + vehicle->SetRadio(true); SUBCASE("24 V") { vehicle->lowVoltage.Set24vAvailableForTest(true); } SUBCASE("110 V") { vehicle->lowVoltage.Set110vAvailableForTest(true); } CHECK(vehicle->RadioPowered()); @@ -16,11 +16,11 @@ TEST_CASE("radio: a radio switched on with the low voltage works") { TEST_CASE("radio: a radio switched off or without the low voltage doesn't") { test::vehicle vehicle{test::definition::load("wagon")}; SUBCASE("switched off") { - vehicle->Radio = false; + vehicle->SetRadio(false); vehicle->lowVoltage.Set24vAvailableForTest(true); } SUBCASE("batteries off") { - vehicle->Radio = true; + vehicle->SetRadio(true); vehicle->lowVoltage.Set24vAvailableForTest(false); vehicle->lowVoltage.Set110vAvailableForTest(false); } @@ -32,27 +32,27 @@ TEST_CASE("radio: a radio switched off or without the low voltage doesn't") { TEST_CASE("radio: the radio fuse is closed by default") { test::vehicle vehicle{test::definition::load("wagon")}; - CHECK(vehicle->RadioFuse); + CHECK(vehicle->RadioFuse()); } TEST_CASE("radio: an opened radio fuse cuts the radio off") { test::vehicle vehicle{test::definition::load("wagon")}; - vehicle->Radio = true; + vehicle->SetRadio(true); vehicle->lowVoltage.Set24vAvailableForTest(true); - vehicle->RadioFuse = false; + vehicle->SetRadioFuse(false); CHECK_FALSE(vehicle->RadioPowered()); - vehicle->RadioFuse = true; + vehicle->SetRadioFuse(true); CHECK(vehicle->RadioPowered()); } TEST_CASE("radio: opening the radio fuse at a standstill resets the radio-stop, as switching the radio off does") { test::vehicle loco{test::definition::fiz("4e_v1/4e")}; loco->lowVoltage.SetBatteryOnForTest(true); - loco->Radio = true; + loco->SetRadio(true); REQUIRE(loco->RadiostopSwitch(true)); loco->SecuritySystemCheck(0.1); - CHECK(loco->RadioStopFlag); - loco->RadioFuse = false; + CHECK(loco->RadioStopFlag()); + loco->SetRadioFuse(false); loco->SecuritySystemCheck(0.1); - CHECK_FALSE(loco->RadioStopFlag); + CHECK_FALSE(loco->RadioStopFlag()); } diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp index d8ed80dcd..9ce81b736 100644 --- a/tests/unit/test_speed_control.cpp +++ b/tests/unit/test_speed_control.cpp @@ -33,13 +33,13 @@ constexpr int dg_hold{5}; constexpr int dg_raise{6}; void move_to(physics::Vehicle &Vehicle, int const Position) { - while (Vehicle.MainCtrlPos < Position && Vehicle.IncMainCtrl(1)) { + while (Vehicle.MainCtrlPos() < Position && Vehicle.IncMainCtrl(1)) { // all the work is done in the condition } - while (Vehicle.MainCtrlPos > Position && Vehicle.DecMainCtrl(1)) { + while (Vehicle.MainCtrlPos() > Position && Vehicle.DecMainCtrl(1)) { // all the work is done in the condition } - REQUIRE(Vehicle.MainCtrlPos == Position); + REQUIRE(Vehicle.MainCtrlPos() == Position); } // the 6Dg started up, its brakes released, its controller through the no power and lowering positions to holding, @@ -81,15 +81,15 @@ TEST_CASE("speed control: the field shunting of the vehicles without a cruise co auto const speed{loco.Vel}; scenario.act("shunt"); CHECK(loco.IncScndCtrl(1)); - CHECK(loco.ScndCtrlPos == 1); + CHECK(loco.ScndCtrlPos() == 1); scenario.wait(10.0); CHECK(loco.Vel > speed); - CHECK(loco.ScndCtrlPos == 1); + 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); + CHECK(loco.ScndCtrlPos() == 0); scenario.wait(5.0); CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); scenario.check(); @@ -107,7 +107,7 @@ TEST_CASE("speed control: the field shunting of the vehicles without a cruise co auto most{0}; for (int i = 0; i < 18; ++i) { scenario.wait(10.0); - most = std::max(most, loco.ScndCtrlPos); + most = std::max(most, loco.ScndCtrlPos()); } CHECK(most == loco.ScndCtrlPosNo); // the driver can't move it @@ -116,7 +116,7 @@ TEST_CASE("speed control: the field shunting of the vehicles without a cruise co scenario.act("notch back"); scenario.notch_back(0); scenario.wait(5.0); - CHECK(loco.ScndCtrlPos == 0); + CHECK(loco.ScndCtrlPos() == 0); scenario.check(); } } @@ -133,7 +133,7 @@ TEST_CASE("speed control: the vehicles whose secondary controller is the cruise scenario.full_power(40.0); scenario.act("cruise control on"); CHECK(unit.IncScndCtrl(1)); - CHECK(unit.ScndCtrlPos == 1); + CHECK(unit.ScndCtrlPos() == 1); CHECK(unit.SpeedCtrlUnit.IsActive); CHECK(unit.SpeedCtrlValue == doctest::Approx(unit.Vel)); auto const held{unit.SpeedCtrlValue}; @@ -141,7 +141,7 @@ TEST_CASE("speed control: the vehicles whose secondary controller is the cruise CHECK(unit.Vel == doctest::Approx(held).epsilon(0.05)); scenario.act("cruise control off"); CHECK(unit.DecScndCtrl(2)); - CHECK(unit.ScndCtrlPos == 0); + CHECK(unit.ScndCtrlPos() == 0); CHECK_FALSE(unit.SpeedCtrlUnit.IsActive); CHECK(unit.SpeedCtrlValue == 0.0); scenario.wait(5.0); @@ -157,10 +157,10 @@ TEST_CASE("speed control: the vehicles whose secondary controller is the cruise REQUIRE(scenario.start_up()); scenario.get_going(); scenario.act("raise"); - while (loco.ScndCtrlPos < 3 && loco.IncScndCtrl(1)) { + while (loco.ScndCtrlPos() < 3 && loco.IncScndCtrl(1)) { // all the work is done in the condition } - REQUIRE(loco.ScndCtrlPos == 3); + REQUIRE(loco.ScndCtrlPos() == 3); scenario.wait(10.0); CHECK(loco.NewSpeed > 0.0); scenario.act("set"); @@ -194,10 +194,10 @@ TEST_CASE("speed control: the field shunting of the vehicles with a cruise contr // 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); + CHECK(loco.ScndCtrlPos() == 0); scenario.wait(110.0); CHECK(loco.Vel > 100.0); - CHECK(loco.ScndCtrlPos == 1); + CHECK(loco.ScndCtrlPos() == 1); CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); // the driver can't move the shunt @@ -219,7 +219,7 @@ TEST_CASE("speed control: the field shunting of the vehicles with a cruise contr auto most{0}; for (int i = 0; i < 9; ++i) { scenario.wait(10.0); - most = std::max(most, loco.ScndCtrlPos); + most = std::max(most, loco.ScndCtrlPos()); } CHECK(loco.Vel > 130.0); CHECK(most == 0); @@ -263,7 +263,7 @@ namespace { void count_shunting(scenario &Scenario, physics::Vehicle 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); + ++(Vehicle.ScndCtrlPos() > 0 ? Shunted : Unshunted); } } @@ -278,7 +278,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the move_to(loco, dg_raise); scenario.wait(30.0); REQUIRE(loco.Vel > 50.0); - REQUIRE(loco.ScndCtrlPos == 1); // the shunt in + 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); @@ -292,7 +292,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the 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 + 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}; @@ -329,7 +329,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the scenario.wait(60.0); CHECK(loco.lineContactors.IsClosed()); CHECK(loco.Vel == doctest::Approx(30.0).epsilon(0.05)); - CHECK(loco.ScndCtrlPos == 0); // out at this speed + CHECK(loco.ScndCtrlPos() == 0); // out at this speed scenario.act("cruise control off"); CHECK(loco.SpeedCtrlSwitch(false)); @@ -373,7 +373,7 @@ TEST_CASE("speed control apart: the ST45's cruise control on its own switch, wit CHECK_FALSE(loco.SpeedCtrlPowerInc()); CHECK(loco.SpeedCtrlValue == 0.0); scenario.wait(5.0); - CHECK(loco.ScndCtrlPos == 0); + CHECK(loco.ScndCtrlPos() == 0); scenario.check(); } @@ -387,13 +387,13 @@ TEST_CASE("speed control apart: the switch of a cruise control without one of it scenario.full_power(20.0); scenario.act("cruise control on"); CHECK(railbus.SpeedCtrlSwitch(true)); - CHECK(railbus.ScndCtrlPos == 1); + 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(railbus.ScndCtrlPos() == 0); CHECK_FALSE(railbus.SpeedCtrlUnit.IsActive); CHECK_FALSE(railbus.IsSpeedCtrlEngaged()); scenario.wait(5.0); diff --git a/tests/unit/test_traction.cpp b/tests/unit/test_traction.cpp index ec049c382..19b417bd0 100644 --- a/tests/unit/test_traction.cpp +++ b/tests/unit/test_traction.cpp @@ -108,7 +108,7 @@ TEST_CASE("traction: the ET42 at the high current setting, its halves in series, scenario.full_power(60.0); // at the high current setting the controller stops at the last series position: the halves' motors stay // in series, at half the voltage each, for a heavy start, and the train crawls - CHECK((et42.RList[et42.MainCtrlPos].Bn > 1) != high); + CHECK((et42.RList[et42.MainCtrlPos()].Bn > 1) != high); CHECK(et42.Vel > (high ? 30.0 : 90.0)); CHECK(et42.Vel < (high ? 50.0 : 110.0)); scenario.act("controller to zero"); @@ -154,14 +154,14 @@ TEST_CASE("traction: the field shunting relays of the diesel-electric locomotive CHECK(controlling.RelayType == relaytype); scenario.get_going(); scenario.full_power(120.0); - CHECK(controlling.ScndCtrlPos == controlling.ScndCtrlPosNo); + CHECK(controlling.ScndCtrlPos() == controlling.ScndCtrlPosNo); auto expected{shunting.begin()}; for (auto const position : {11, 10, 7, 3}) { CAPTURE(position); scenario.act(std::format("notch back to {}", position)); scenario.notch_back(position); scenario.wait(15.0); - CHECK(controlling.ScndCtrlPos == *expected++); + CHECK(controlling.ScndCtrlPos() == *expected++); } stop(scenario); scenario.check(); diff --git a/tests/unit/test_uc_steps.cpp b/tests/unit/test_uc_steps.cpp index eb1b26fa4..a25397b23 100644 --- a/tests/unit/test_uc_steps.cpp +++ b/tests/unit/test_uc_steps.cpp @@ -26,25 +26,25 @@ void get_ready(vehicle &Railbus, test::track const &Track) { for (int i = 0; i < 3 && Railbus->DirActive <= 0; ++i) { Railbus->DirectionForward(); } - while (Railbus->MainCtrlPos < hold && Railbus->IncMainCtrl(1)) { + while (Railbus->MainCtrlPos() < hold && Railbus->IncMainCtrl(1)) { ; } - while (Railbus->MainCtrlPos > hold && Railbus->DecMainCtrl(1)) { + while (Railbus->MainCtrlPos() > hold && Railbus->DecMainCtrl(1)) { ; } - REQUIRE(Railbus->MainCtrlPos == hold); + REQUIRE(Railbus->MainCtrlPos() == hold); Railbus.run(2.0, Track); REQUIRE(Railbus->eimic == doctest::Approx(0.0)); } void move_to(vehicle &Railbus, int const Position) { - while (Railbus->MainCtrlPos < Position && Railbus->IncMainCtrl(1)) { + while (Railbus->MainCtrlPos() < Position && Railbus->IncMainCtrl(1)) { ; } - while (Railbus->MainCtrlPos > Position && Railbus->DecMainCtrl(1)) { + while (Railbus->MainCtrlPos() > Position && Railbus->DecMainCtrl(1)) { ; } - REQUIRE(Railbus->MainCtrlPos == Position); + REQUIRE(Railbus->MainCtrlPos() == Position); } bool on_step(double const Value, double const Step) { diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index e764c5ba9..1ef9a3256 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -135,7 +135,7 @@ vehicle::vehicle(definition const &Definition, double Velocity, std::string cons if (false == m_physics->CheckLocomotiveParameters(driveractive, (Velocity > 0 ? 1 : -1) * Cab)) { throw definition_error("parameters mismatch in the test vehicle definition"); } - m_physics->MainCtrlPos = m_physics->MainCtrlNoPowerPos(); + m_physics->SetMainCtrlPos(m_physics->MainCtrlNoPowerPos()); m_physics->brakes.independentPosition = 0.0; if (driveractive) { m_physics->brakes.handlePosition = static_cast(std::floor(m_physics->brakes.driverValve->GetPos(Cab == 0 ? bh_NP : bh_RP))); diff --git a/vehicle/Camera.cpp b/vehicle/Camera.cpp index 51b13e87e..e7346b5bb 100644 --- a/vehicle/Camera.cpp +++ b/vehicle/Camera.cpp @@ -197,7 +197,7 @@ void TCamera::Update() auto movement { Velocity * -2.0 }; movement.y = -movement.y; if( auto const *owner { ( m_owner->Mechanik ? m_owner->Mechanik : m_owner->ctOwner ) }; owner && owner->Occupied() - && owner->Occupied()->CabOccupied < 0 ) { + && owner->Occupied()->CabOccupied() < 0 ) { movement *= -1.f; movement.y = -movement.y; } diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index 81b807301..6f87b81d3 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -64,7 +64,7 @@ void TController::Activation() // reset controls ZeroSpeed(); ZeroDirection(); - occupied->CabOccupied = occupied->CabActive; // użytkownik moze zmienić CabOccupied wychodząc + occupied->SetCabOccupied(occupied->CabActive); // użytkownik moze zmienić CabOccupied wychodząc occupied->CabDeactivisation(); // tak jest w Train.cpp if (pVehicle->physics->Couplers[iDirectionOrder < 0 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)) { ZeroLocalBrake(); @@ -93,7 +93,7 @@ void TController::Activation() pVehicle->Mechanik = targetvehicledriver; // wsadzamy tego, co ewentualnie był (podwójna trakcja) // NOTE: having caboccupied != 0 (by swapping in the driver from the target vehicle) may lead to dysfunctional brake // TODO: investigate and resolve if necessary - pVehicle->physics->CabOccupied = targetvehicle->physics->CabOccupied; + pVehicle->physics->SetCabOccupied(targetvehicle->physics->CabOccupied()); if( pVehicle->Mechanik ) { // not guaranteed, as target vehicle can be empty pVehicle->Mechanik->BrakeLevelSet( pVehicle->physics->brakes.handlePosition ); } @@ -117,7 +117,7 @@ void TController::Activation() mvControlling->CurrentSwitch(OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt) || fMass > 224000.0); // do tego na wzniesieniu może nie dać rady na liniowym } // Ra: to przełączanie poniżej jest tu bez sensu - occupied->CabOccupied = iDirection; // aktywacja kabiny w prowadzonym pojeżdzie (silnikowy może być odwrotnie?) + occupied->SetCabOccupied(iDirection); // aktywacja kabiny w prowadzonym pojeżdzie (silnikowy może być odwrotnie?) occupied->CabActivisation(); // uruchomienie kabin w członach DirectionForward(true); // nawrotnik do przodu occupied->SpringBrakeActivate( initialspringbrakestate ); @@ -557,7 +557,7 @@ void TController::DirectionForward(bool forward) { // ustawienie jazdy do przodu dla true i do tyłu dla false (zależy od kabiny) ZeroSpeed( true ); // TODO: check if force switch is needed anymore here // HACK: make sure the master controller isn't set in position which prevents direction change - mvControlling->MainCtrlPos = std::min( mvControlling->MainCtrlPos, mvControlling->MainCtrlMaxDirChangePos ); + mvControlling->SetMainCtrlPos(std::min( mvControlling->MainCtrlPos(), mvControlling->MainCtrlMaxDirChangePos )); if( forward ) { // do przodu w obecnej kabinie @@ -577,7 +577,7 @@ void TController::DirectionForward(bool forward) } if( occupied->TrainType == train_type::sn61 ) { // specjalnie dla SN61 żeby nie zgasł - while( mvControlling->RList[mvControlling->MainCtrlPos].Mn == 0 + while( mvControlling->RList[mvControlling->MainCtrlPos()].Mn == 0 && mvControlling->IncMainCtrl(1) ) { ; // all work is done in the header } @@ -678,7 +678,7 @@ TController::determine_consist_state() { cue_action( driver_hint::cabactivation ); } else if (!occupied->AutomaticCabActivation - && ( occupied->CabActive == -occupied->CabOccupied || !occupied->CabMaster || !occupied->lowVoltage.Is24vAvailable() ) ) + && ( occupied->CabActive == -occupied->CabOccupied() || !occupied->CabMaster || !occupied->lowVoltage.Is24vAvailable() ) ) { cue_action( driver_hint::cabdeactivation ); } @@ -771,7 +771,7 @@ TController::determine_consist_state() { || vehicle->Couplers[VehicleEnd::rear].stretch_duration > 0.0; // check door state { - auto const switchsides{ p->DirectionGet() != (iDirection == 0 ? occupied->CabOccupied : iDirection) }; + auto const switchsides{ p->DirectionGet() != (iDirection == 0 ? occupied->CabOccupied() : iDirection) }; auto const &rightdoor { vehicle->Doors.instances[ ( switchsides ? VehicleSide::left : VehicleSide::right ) ] }; auto const &leftdoor { vehicle->Doors.instances[ ( switchsides ? VehicleSide::right : VehicleSide::left ) ] }; if( vehicle->Doors.close_control != control_t::autonomous ) { diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index 793d182b2..30f6a7e29 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -282,24 +282,24 @@ bool TController::IncBrakeEIM() break; } case 1: { - OK = occupied->MainCtrlPos > 0; + OK = occupied->MainCtrlPos() > 0; if( OK ) - occupied->MainCtrlPos = 0; + occupied->SetMainCtrlPos(0); break; } case 2: { // the braking position, above the emergency brake one where the controller has it auto const brakepos{1 + occupied->EIMCtrlEmergencyPositions()}; - OK = occupied->MainCtrlPos > brakepos; + OK = occupied->MainCtrlPos() > brakepos; if( OK ) - occupied->MainCtrlPos = brakepos; + occupied->SetMainCtrlPos(brakepos); break; } case 3: { if( occupied->UniCtrlIntegratedLocalBrakeCtrl ) { - OK = occupied->MainCtrlPos > 0; + OK = occupied->MainCtrlPos() > 0; if( OK ) - occupied->MainCtrlPos = 0; + occupied->SetMainCtrlPos(0); } else { OK = occupied->IncLocalBrakeLevel( 1 ); @@ -465,22 +465,22 @@ bool TController::DecBrakeEIM() break; } case 1: { - OK = occupied->MainCtrlPos < 2; + OK = occupied->MainCtrlPos() < 2; if( OK ) - occupied->MainCtrlPos = 2; + occupied->SetMainCtrlPos(2); break; } case 2: { auto const neutralpos{occupied->MainCtrlNoPowerPos()}; - OK = occupied->MainCtrlPos < neutralpos; + OK = occupied->MainCtrlPos() < neutralpos; if( OK ) - occupied->MainCtrlPos = neutralpos; + occupied->SetMainCtrlPos(neutralpos); break; } case 3: { - OK = occupied->MainCtrlPos < occupied->MainCtrlMaxDirChangePos; + OK = occupied->MainCtrlPos() < occupied->MainCtrlMaxDirChangePos; if( OK ) - occupied->MainCtrlPos = occupied->MainCtrlMaxDirChangePos; + occupied->SetMainCtrlPos(occupied->MainCtrlMaxDirChangePos); break; } } @@ -526,8 +526,8 @@ bool TController::IncSpeed() // to build up speed to 30/40 km/h for passenger/cargo train (10 km/h less if going uphill) auto const sufficienttractionforce{std::abs(mvControlling->Ft) * ControlledEnginesCount > (IsHeavyCargoTrain ? 75 : 50) * 1000.0}; auto const sufficientacceleration{AbsAccS >= (IsHeavyCargoTrain ? 0.03 : IsCargoTrain ? 0.06 : 0.09)}; - auto const seriesmodefieldshunting{mvControlling->ScndCtrlPos > 0 && mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1}; - auto const parallelmodefieldshunting{mvControlling->ScndCtrlPos > 0 && mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1}; + auto const seriesmodefieldshunting{mvControlling->ScndCtrlPos() > 0 && mvControlling->RList[mvControlling->MainCtrlPos()].Bn == 1}; + auto const parallelmodefieldshunting{mvControlling->ScndCtrlPos() > 0 && mvControlling->RList[mvControlling->MainCtrlPos()].Bn > 1}; auto const minvoltage{(pantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? pantographUnit->EnginePowerSource.CollectorParameters.MinV : 0.0)}; auto const maxvoltage{(pantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? pantographUnit->EnginePowerSource.CollectorParameters.MaxV : 0.0)}; auto const seriesmodevoltage{std::lerp(minvoltage, maxvoltage, IsHeavyCargoTrain ? 0.35 : 0.40)}; @@ -536,11 +536,11 @@ bool TController::IncSpeed() occupied->Vel <= (IsCargoTrain ? 40 : 30) + (seriesmodefieldshunting ? 5 : 0) - (fAccGravity < -0.025 ? 10 : 0)); // when not in series mode use the first available parallel mode configuration until 50/60 km/h for passenger/cargo train // (if there's only one parallel mode configuration it'll be used regardless of current speed) - auto const usefieldshunting = mvControlling->lineContactors.IsClosed() && mvControlling->RList[mvControlling->MainCtrlPos].R < 0.01 && false == mvControlling->IsScndCtrlLockedByMainCtrl() && - (useseriesmode ? mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1 : + auto const usefieldshunting = mvControlling->lineContactors.IsClosed() && mvControlling->RList[mvControlling->MainCtrlPos()].R < 0.01 && false == mvControlling->IsScndCtrlLockedByMainCtrl() && + (useseriesmode ? mvControlling->RList[mvControlling->MainCtrlPos()].Bn == 1 : true == sufficientacceleration && true == sufficienttractionforce && occupied->Vel <= (IsCargoTrain ? 60 : 50) + (parallelmodefieldshunting ? 5 : 0) ? - mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 : - mvControlling->MainCtrlPos == mvControlling->MainCtrlPosNo); + mvControlling->RList[mvControlling->MainCtrlPos()].Bn > 1 : + mvControlling->MainCtrlPos() == mvControlling->MainCtrlPosNo); // if needed enable high threshold for overload relay... if (mvControlling->TrainType != train_type::et42) @@ -550,13 +550,13 @@ bool TController::IncSpeed() if (mvControlling->Imax < mvControlling->ImaxHi) { // to enable this setting we'll typically need the main controller in series mode (which is not guaranteed) - if (mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1) + if (mvControlling->RList[mvControlling->MainCtrlPos()].Bn > 1) { if (false == mvControlling->IsScndCtrlNoPowerPos()) { mvControlling->DecScndCtrl(2); } - while (false == mvControlling->IsMainCtrlNoPowerPos() && mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1) + while (false == mvControlling->IsMainCtrlNoPowerPos() && mvControlling->RList[mvControlling->MainCtrlPos()].Bn > 1) { mvControlling->DecMainCtrl(1); // kręcimy nastawnik jazdy o 1 wstecz } @@ -575,7 +575,7 @@ bool TController::IncSpeed() } double Vs = 99999; - if (usefieldshunting ? mvControlling->ScndCtrlPos < mvControlling->ScndCtrlPosNo : mvControlling->MainCtrlPos < mvControlling->MainCtrlPosNo) + if (usefieldshunting ? mvControlling->ScndCtrlPos() < mvControlling->ScndCtrlPosNo : mvControlling->MainCtrlPos() < mvControlling->MainCtrlPosNo) { Vs = ESMVelocity(!usefieldshunting); } @@ -594,7 +594,7 @@ bool TController::IncSpeed() else { // jeśli ustawiony bocznik to bocznik na zero po chamsku - if (mvControlling->ScndCtrlPos) + if (mvControlling->ScndCtrlPos()) { mvControlling->DecScndCtrl(2); } @@ -602,7 +602,7 @@ bool TController::IncSpeed() // don't draw too much power; // keep from dropping into series mode when entering/using parallel mode, and from shutting down in the series mode auto const sufficientpowermargin{fVoltage - - (mvControlling->RList[std::min(mvControlling->MainCtrlPos + 1, mvControlling->MainCtrlPosNo)].Bn == 1 ? minvoltage : seriesmodevoltage) > + (mvControlling->RList[std::min(mvControlling->MainCtrlPos() + 1, mvControlling->MainCtrlPosNo)].Bn == 1 ? minvoltage : seriesmodevoltage) > (IsHeavyCargoTrain ? 100.0 : 75.0) * ControlledEnginesCount}; OK = sufficientpowermargin && false == mvControlling->DelayCtrlFlag ? mvControlling->IncMainCtrl(1) : true; @@ -708,7 +708,7 @@ bool TController::IncSpeed() if (true == Ready) { bool max = mvControlling->Vel > mvControlling->diesel.fullEngageMinVelocity - || (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos > 0); + || (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos() > 0); DizelPercentage = max ? 100 : 1; } break; @@ -716,10 +716,10 @@ bool TController::IncSpeed() else { if( true == Ready ) { if( mvControlling->Vel > mvControlling->diesel.fullEngageMinVelocity - && mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 ) { + && mvControlling->RList[mvControlling->MainCtrlPos()].Mn > 0 ) { OK = mvControlling->IncMainCtrl( 1 ); } - if( mvControlling->RList[ mvControlling->MainCtrlPos ].Mn == 0 ) { + if( mvControlling->RList[ mvControlling->MainCtrlPos() ].Mn == 0 ) { OK = mvControlling->IncMainCtrl( 1 ); } } @@ -796,11 +796,11 @@ bool TController::DecSpeed(bool force) if (mvControlling->Vel > mvControlling->diesel.fullEngageMinVelocity) { - if (mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0) + if (mvControlling->RList[mvControlling->MainCtrlPos()].Mn > 0) OK = mvControlling->DecMainCtrl(1); } else { - while( mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 + while( mvControlling->RList[mvControlling->MainCtrlPos()].Mn > 0 && mvControlling->MainCtrlPowerPos() > 1 ) { OK = mvControlling->DecMainCtrl( 1 ); } @@ -823,23 +823,23 @@ bool TController::IncSpeedEIM() { OK = mvControlling->IncMainCtrl( 1 ); break; case 1: - OK = mvControlling->MainCtrlPos < 6; + OK = mvControlling->MainCtrlPos() < 6; if( OK ) { - mvControlling->MainCtrlPos = 6; + mvControlling->SetMainCtrlPos(6); } /* // TBD, TODO: set position based on desired acceleration? - OK = mvControlling->MainCtrlPos < mvControlling->MainCtrlPosNo; + OK = mvControlling->MainCtrlPos() < mvControlling->MainCtrlPosNo; if( OK ) { - mvControlling->MainCtrlPos = safe_clamp( mvControlling->MainCtrlPos + 1, 6, mvControlling->MainCtrlPosNo ); + mvControlling->SetMainCtrlPos(safe_clamp( mvControlling->MainCtrlPos() + 1, 6, mvControlling->MainCtrlPosNo )); } */ break; case 2: { auto const powerpos{4 + mvControlling->EIMCtrlEmergencyPositions()}; - OK = mvControlling->MainCtrlPos < powerpos; + OK = mvControlling->MainCtrlPos() < powerpos; if( OK ) { - mvControlling->MainCtrlPos = powerpos; + mvControlling->SetMainCtrlPos(powerpos); } break; } @@ -856,9 +856,9 @@ bool TController::DecSpeedEIM( int const Amount ) break; } case 1: { - OK = mvControlling->MainCtrlPos > 4; + OK = mvControlling->MainCtrlPos() > 4; if( OK ) { - mvControlling->MainCtrlPos = 4; + mvControlling->SetMainCtrlPos(4); } break; } @@ -871,9 +871,9 @@ bool TController::DecSpeedEIM( int const Amount ) } else { auto const holdpos{2 + mvControlling->EIMCtrlEmergencyPositions()}; - OK = mvControlling->MainCtrlPos > holdpos; + OK = mvControlling->MainCtrlPos() > holdpos; if( OK ) { - mvControlling->MainCtrlPos = holdpos; + mvControlling->SetMainCtrlPos(holdpos); } } break; @@ -916,7 +916,7 @@ void TController::SpeedSet() { // TODO: sprawdzanie innego czlonu //if (!FuseFlagCheck()) if( ( false == drivingFlags.incSpeed ) ) { // przetok rozłączać od razu (no dependency on fActionTime) - while( mvControlling->MainCtrlPos + while( mvControlling->MainCtrlPos() && mvControlling->DecMainCtrl(1) ) { ; // na zero } @@ -934,14 +934,14 @@ void TController::SpeedSet() { occupied->DirectionForward(); //żeby EN57 jechały na drugiej nastawie } - if( mvControlling->MainCtrlPos > 0 + if( mvControlling->MainCtrlPos() > 0 && false == mvControlling->lineContactors.IsClosed() ) { // jak niby jedzie, ale ma rozłączone liniowe to na zero i czekać na przewalenie kułakowego mvControlling->DecMainCtrl( 2 ); } else { // ruch nastawnika uzależniony jest od aktualnie ustawionej pozycji - switch( mvControlling->MainCtrlPos ) { + switch( mvControlling->MainCtrlPos() ) { case 0: if( mvControlling->MainCtrlActualPos ) { // jeśli kułakowy nie jest wyzerowany to czekać na wyzerowanie @@ -965,7 +965,7 @@ void TController::SpeedSet() { mvControlling->IncMainCtrl( 1 ); // bocznik 3 } } - if( mvControlling->MainCtrlPos ) // jak załączył pozycję + if( mvControlling->MainCtrlPos() ) // jak załączył pozycję { fActionTime = -5.0; // niech trochę potrzyma // mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania @@ -983,15 +983,15 @@ void TController::SpeedSet() { if( mvControlling->Imax * mvControlling->EngineVoltage / ( fMass * fAccGravity ) < -2.8 ) // a na niskim się za szybko nie pojedzie { // włączenie wysokiego rozruchu; // (I*U)[A*V=W=kg*m*m/sss]/(m[kg]*a[m/ss])=v[m/s]; 2.8m/ss=10km/h - if( mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1 ) { // jeśli jedzie na równoległym, to zbijamy do szeregowego, aby włączyć wysoki rozruch - if( mvControlling->ScndCtrlPos > 0 ) { // jeżeli jest bocznik + if( mvControlling->RList[ mvControlling->MainCtrlPos() ].Bn > 1 ) { // jeśli jedzie na równoległym, to zbijamy do szeregowego, aby włączyć wysoki rozruch + if( mvControlling->ScndCtrlPos() > 0 ) { // jeżeli jest bocznik mvControlling->DecScndCtrl( 2 ); // wyłączyć bocznik, bo może blokować skręcenie NJ } do { // skręcanie do bezoporowej na szeregowym mvControlling->DecMainCtrl( 1 ); // kręcimy nastawnik jazdy o 1 wstecz } while( ( false == mvControlling->IsMainCtrlNoPowerPos() ) - && ( mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1 ) ); // oporowa zapętla + && ( mvControlling->RList[ mvControlling->MainCtrlPos() ].Bn > 1 ) ); // oporowa zapętla } if( mvControlling->Imax < mvControlling->ImaxHi ) { // jeśli da się na wysokim mvControlling->CurrentSwitch( true ); // rozruch wysoki (za to może się ślizgać) @@ -1002,7 +1002,7 @@ void TController::SpeedSet() { } // if (Im>Imin) } if( std::fabs( mvControlling->Im ) > 0.96 * mvControlling->Imax ) {// jeśli prąd jest duży (można 690 na 750) - if( mvControlling->ScndCtrlPos > 0 ) { // jeżeli jest bocznik + if( mvControlling->ScndCtrlPos() > 0 ) { // jeżeli jest bocznik mvControlling->DecScndCtrl( 2 ); // zmniejszyć bocznik } else { @@ -1033,27 +1033,27 @@ void TController::SpeedSet() { } case TEngineType::DieselEngine: { // Ra 2014-06: "automatyczna" skrzynia biegów... - auto const &motorparams { mvControlling->MotorParam[ mvControlling->ScndCtrlPos ] }; - auto const velocity { ( mvControlling->ShuntMode ? mvControlling->AnPos : 1.0 ) * mvControlling->Vel }; + auto const &motorparams { mvControlling->MotorParam[ mvControlling->ScndCtrlPos() ] }; + auto const velocity { ( mvControlling->ShuntMode ? mvControlling->AnPos() : 1.0 ) * mvControlling->Vel }; if( false == motorparams.AutoSwitch ) { // gdy biegi ręczne // jak prędkość większa niż procent maksymalnej na danym biegu, wrzucić wyższy if( velocity > 0.75 * motorparams.mfi ) { // ...presuming there is a higher gear - if( mvControlling->ScndCtrlPos < mvControlling->ScndCtrlPosNo ) { + if( mvControlling->ScndCtrlPos() < mvControlling->ScndCtrlPosNo ) { mvControlling->DecMainCtrl( 2 ); while( mvControlling->IncScndCtrl(1) - && mvControlling->MotorParam[mvControlling->ScndCtrlPos].mIsat == 0.0 ) { // jeśli bieg jałowy to kolejny + && mvControlling->MotorParam[mvControlling->ScndCtrlPos()].mIsat == 0.0 ) { // jeśli bieg jałowy to kolejny ; } } } // jak prędkość mniejsza niż minimalna na danym biegu, wrzucić niższy - else if( velocity < motorparams.fi && mvControlling->ScndCtrlPos > 1 ) { + else if( velocity < motorparams.fi && mvControlling->ScndCtrlPos() > 1 ) { // ... but ensure we don't switch all way down to 0 mvControlling->DecMainCtrl(2); - while (mvControlling->ScndCtrlPos > 1 // repeat the entry check as we're working in a loop - && mvControlling->DecScndCtrl(1) && mvControlling->MotorParam[mvControlling->ScndCtrlPos].mIsat == 0.0) + while (mvControlling->ScndCtrlPos() > 1 // repeat the entry check as we're working in a loop + && mvControlling->DecScndCtrl(1) && mvControlling->MotorParam[mvControlling->ScndCtrlPos()].mIsat == 0.0) { // jeśli bieg jałowy to kolejny ; } @@ -1086,7 +1086,7 @@ void TController::SpeedCntrl(double DesiredSpeed) mvControlling->DecScndCtrl(2); DesiredSpeed = 0; } - else if (mvControlling->ScndCtrlPos < 1) { + else if (mvControlling->ScndCtrlPos() < 1) { mvControlling->IncScndCtrl(1); } mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); @@ -1100,8 +1100,8 @@ void TController::SpeedCntrl(double DesiredSpeed) else if (mvControlling->ScndCtrlPosNo > 1 && !occupied->SpeedCtrlTypeTime) { int DesiredPos = 1 + mvControlling->ScndCtrlPosNo * ((DesiredSpeed - 1.0) / mvControlling->Vmax); - while( mvControlling->ScndCtrlPos > DesiredPos && true == mvControlling->DecScndCtrl(1) ) { ; } // all work is done in the condition loop - while( mvControlling->ScndCtrlPos < DesiredPos && true == mvControlling->IncScndCtrl(1) ) { ; } // all work is done in the condition loop + while( mvControlling->ScndCtrlPos() > DesiredPos && true == mvControlling->DecScndCtrl(1) ) { ; } // all work is done in the condition loop + while( mvControlling->ScndCtrlPos() < DesiredPos && true == mvControlling->IncScndCtrl(1) ) { ; } // all work is done in the condition loop } if( mvControlling->SpeedCtrlUnit.PowerStep > 0 && mvControlling->IsSpeedCtrlEngaged() ) { @@ -1167,11 +1167,11 @@ void TController::SetTimeControllers() { if (occupied->EIMCtrlType == 1) //traxx { - if (occupied->LocalBrakePosA > 0.95) occupied->MainCtrlPos = 0; + if (occupied->LocalBrakePosA > 0.95) occupied->SetMainCtrlPos(0); } else if (occupied->EIMCtrlType == 2) //elf { - if (occupied->LocalBrakePosA > 0.95) occupied->MainCtrlPos = 1; + if (occupied->LocalBrakePosA > 0.95) occupied->SetMainCtrlPos(1); } } */ @@ -1191,9 +1191,9 @@ void TController::SetTimeControllers() if (occupied->ScndCtrlPosNo == 4) { if (occupied->NewSpeed + 0.1 < SpeedCntrlVel) - occupied->ScndCtrlPos = 3; + occupied->SetScndCtrlPos(3); if (occupied->NewSpeed - 0.1 > SpeedCntrlVel) - occupied->ScndCtrlPos = 1; + occupied->SetScndCtrlPos(1); } } //5. Check Main Controller in Dizels @@ -1204,8 +1204,8 @@ void TController::SetTimeControllers() DizelPercentage_Speed = DizelPercentage; //wstepnie procenty auto MinVel{ std::min(mvControlling->torqueConverter.lockupSpeed, mvControlling->Vmax / 6) }; //minimal velocity //when speed controll unit is active - start with the procedure - if (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos > 0) { - if (mvControlling->ScndCtrlPos > 0 && mvControlling->Vel < 1 + mvControlling->SpeedCtrlUnit.StartVelocity && DizelPercentage > 0) + if (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos() > 0) { + if (mvControlling->ScndCtrlPos() > 0 && mvControlling->Vel < 1 + mvControlling->SpeedCtrlUnit.StartVelocity && DizelPercentage > 0) DizelPercentage_Speed = 101; //keep last position to start } else if (VelDesired > MinVel) //more power for faster ride @@ -1250,11 +1250,11 @@ void TController::SetTimeControllers() DizelPercentage_Speed > DizelActualPercentage ? PosInc : PosDec ) }; - while( mvControlling->MainCtrlPos > DesiredPos ) { mvControlling->DecMainCtrl( 1 ); } - while( mvControlling->MainCtrlPos < DesiredPos ) { mvControlling->IncMainCtrl( 1 ); } + while( mvControlling->MainCtrlPos() > DesiredPos ) { mvControlling->DecMainCtrl( 1 ); } + while( mvControlling->MainCtrlPos() < DesiredPos ) { mvControlling->IncMainCtrl( 1 ); } } if (BrakeCtrlPosition < 0.1) //jesli nie hamuje - occupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos].mode); //zeby nie bruzdzilo machanie zespolonym + occupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos()].mode); //zeby nie bruzdzilo machanie zespolonym } else //5.2. Analog direct controller @@ -1263,7 +1263,7 @@ void TController::SetTimeControllers() int MaxPos = mvControlling->MainCtrlPosNo; int MinPos = MaxPos; for (int i = MaxPos; i > 1 && mvControlling->RList[i].Mn > 0; i--) MinPos = i; - if (MaxPos > MinPos && mvControlling->MainCtrlPos > 0 && AccDesired > 0) + if (MaxPos > MinPos && mvControlling->MainCtrlPos() > 0 && AccDesired > 0) { double Factor = 5 * mvControlling->Vmax / (mvControlling->Vmax + mvControlling->Vel); int DesiredPos = MinPos + (MaxPos - MinPos)*(VelDesired > mvControlling->Vel ? (VelDesired - mvControlling->Vel) / Factor : 0); @@ -1271,9 +1271,9 @@ void TController::SetTimeControllers() if (DesiredPos < MinPos) DesiredPos = MinPos; if (!mvControlling->SlippingWheels) { - while (mvControlling->MainCtrlPos > DesiredPos) mvControlling->DecMainCtrl(1); + while (mvControlling->MainCtrlPos() > DesiredPos) mvControlling->DecMainCtrl(1); if (mvControlling->Vel>mvControlling->diesel.fullEngageMinVelocity) - while (mvControlling->MainCtrlPos < DesiredPos) mvControlling->IncMainCtrl(1); + while (mvControlling->MainCtrlPos() < DesiredPos) mvControlling->IncMainCtrl(1); } } } @@ -1303,11 +1303,11 @@ void TController::SetTimeControllers() auto const DesiredPos{(AccDesired > AbsAccS + 0.05 ? PosInc : AccDesired < AbsAccS - 0.05 ? PosDec : PosKeep)}; - while (mvControlling->MainCtrlPos > DesiredPos && mvControlling->DecMainCtrl(1)) + while (mvControlling->MainCtrlPos() > DesiredPos && mvControlling->DecMainCtrl(1)) { ; } - while (mvControlling->MainCtrlPos < DesiredPos && mvControlling->IncMainCtrl(1)) + while (mvControlling->MainCtrlPos() < DesiredPos && mvControlling->IncMainCtrl(1)) { ; } @@ -1350,20 +1350,20 @@ void TController::CheckTimeControllers() { if (occupied->EIMCtrlType == 1) //traxx { - if (occupied->MainCtrlPos > 3) occupied->MainCtrlPos = 5; - if (occupied->MainCtrlPos < 3) occupied->MainCtrlPos = 1; + if (occupied->MainCtrlPos() > 3) occupied->SetMainCtrlPos(5); + if (occupied->MainCtrlPos() < 3) occupied->SetMainCtrlPos(1); } else if (occupied->EIMCtrlType == 2) //elf { auto const emergencypositions{occupied->EIMCtrlEmergencyPositions()}; - if (occupied->eimic > 0) occupied->MainCtrlPos = 3 + emergencypositions; - if (occupied->eimic < 0) occupied->MainCtrlPos = 2 + emergencypositions; + if (occupied->eimic > 0) occupied->SetMainCtrlPos(3 + emergencypositions); + if (occupied->eimic < 0) occupied->SetMainCtrlPos(2 + emergencypositions); } } //4. Check Speed Control System if (occupied->EngineType == TEngineType::ElectricInductionMotor && occupied->ScndCtrlPosNo > 1 && occupied->SpeedCtrlTypeTime && occupied->ScndCtrlPosNo == 4) { - occupied->ScndCtrlPos = 2; + occupied->SetScndCtrlPos(2); } //5. Check Main Controller in Dizels @@ -1380,11 +1380,11 @@ void TController::CheckTimeControllers() } if (BrakeCtrlPosition < 0.1) //jesli nie hamuje { - if (DizelActualPercentage >= DizelPercentage_Speed && mvControlling->MainCtrlPos > NeutralPos) - while (mvControlling->MainCtrlPos > NeutralPos) mvControlling->DecMainCtrl(1); - if (DizelActualPercentage <= DizelPercentage_Speed && mvControlling->MainCtrlPos < NeutralPos) - while (mvControlling->MainCtrlPos < NeutralPos) mvControlling->IncMainCtrl(1); - occupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos].mode); //zeby nie bruzdzilo machanie zespolonym + if (DizelActualPercentage >= DizelPercentage_Speed && mvControlling->MainCtrlPos() > NeutralPos) + while (mvControlling->MainCtrlPos() > NeutralPos) mvControlling->DecMainCtrl(1); + if (DizelActualPercentage <= DizelPercentage_Speed && mvControlling->MainCtrlPos() < NeutralPos) + while (mvControlling->MainCtrlPos() < NeutralPos) mvControlling->IncMainCtrl(1); + occupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos()].mode); //zeby nie bruzdzilo machanie zespolonym } } }; diff --git a/vehicle/ai/doors.cpp b/vehicle/ai/doors.cpp index e751dc938..3a3aa7eef 100644 --- a/vehicle/ai/doors.cpp +++ b/vehicle/ai/doors.cpp @@ -186,7 +186,7 @@ TController::control_doors() { // HACK: crude way to deal with automatic door opening on W4 preventing further ride // for human-controlled vehicles with no door control and dynamic brake auto-activating with door open // TODO: check if this situation still happens and the hack is still needed - if( false == AIControllFlag && (mvControlling->EngineType == TEngineType::DieselEngine ? mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 : mvControlling->MainCtrlPowerPos() > 0) ) { + if( false == AIControllFlag && (mvControlling->EngineType == TEngineType::DieselEngine ? mvControlling->RList[mvControlling->MainCtrlPos()].Mn > 0 : mvControlling->MainCtrlPowerPos() > 0) ) { // for diesel engines react when engine is put past idle revolutions // for others straightforward master controller check Doors(false); diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp index 77bbcbd52..242a98a80 100644 --- a/vehicle/ai/force.cpp +++ b/vehicle/ai/force.cpp @@ -74,7 +74,7 @@ TController::control_tractive_and_braking_force() { control_motor_connectors(); // if the radio-stop was issued don't waste effort trying to fight it - if( true == occupied->RadioStopFlag // radio-stop + if( true == occupied->RadioStopFlag() // radio-stop && occupied->Vel > EU07_AI_NOMOVEMENT ) { // and still moving cue_action( driver_hint::mastercontrollersetzerospeed ); // just throttle down... return; // ...and don't touch any other controls @@ -96,7 +96,7 @@ TController::control_tractive_and_braking_force() { #if LOGVELOCITY WriteLog("BrakePos=" + AnsiString(occupied->brakes.handlePosition) + ", MainCtrl=" + - AnsiString(mvControlling->MainCtrlPos)); + AnsiString(mvControlling->MainCtrlPos())); #endif } diff --git a/vehicle/ai/obstacles.cpp b/vehicle/ai/obstacles.cpp index 28d8cf263..b0ef203b7 100644 --- a/vehicle/ai/obstacles.cpp +++ b/vehicle/ai/obstacles.cpp @@ -388,7 +388,7 @@ TController::scan_obstacles( double const Range ) { routescandirection = NumberOf( VehicleEnd::rear ); } /* - if( pVehicle->physics->CabOccupied < 0 ) { + if( pVehicle->physics->CabOccupied() < 0 ) { // flip the scan direction in the rear cab routescandirection ^= routescandirection; } diff --git a/vehicle/ai/orders.cpp b/vehicle/ai/orders.cpp index 0c1acba8f..34e4f44b7 100644 --- a/vehicle/ai/orders.cpp +++ b/vehicle/ai/orders.cpp @@ -304,7 +304,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N if (occupied->V!=0.0) iDirectionOrder=occupied->V>0?1:-1; else - iDirectionOrder=occupied->CabOccupied; + iDirectionOrder=occupied->CabOccupied(); if (!iDirectionOrder) iDirectionOrder=1; } */ @@ -961,7 +961,7 @@ TController::UpdateObeyTrain() { // radio message tsGuardSignal.owner( pVehicle ); /* - tsGuardSignal.offset( { 0.f, 2.f, pVehicle->physics->Dim.L * 0.4f * ( pVehicle->physics->CabOccupied < 0 ? -1 : 1 ) } ); + tsGuardSignal.offset( { 0.f, 2.f, pVehicle->physics->Dim.L * 0.4f * ( pVehicle->physics->CabOccupied() < 0 ? -1 : 1 ) } ); tsGuardSignal.play( sound_flags::exclusive ); */ simulation::radio_message( &tsGuardSignal, iGuardRadio ); diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp index 8430beac7..08a40f14a 100644 --- a/vehicle/ai/physicslog.cpp +++ b/vehicle/ai/physicslog.cpp @@ -75,8 +75,8 @@ std::string TController::physicslog_line() const { << occupied->brakes.cylinderPressure << " " << occupied->brakePipe.Pressure() << " " << mvControlling->Im << " " - << int(mvControlling->MainCtrlPos) << " " - << int(mvControlling->ScndCtrlPos) << " " + << int(mvControlling->MainCtrlPos()) << " " + << int(mvControlling->ScndCtrlPos()) << " " << occupied->brakes.handlePositionSmooth << " " << occupied->brakes.independentPosition << " " << int(mvControlling->DirActive) << " " diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index 267671e4a..9d0bf70c0 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -308,12 +308,12 @@ TController::control_horns( double const Timedelta ) { // horn control if( fWarningDuration > 0.0 ) { // jeśli pozostało coś do wytrąbienia trąbienie trwa nadal - if( occupied->WarningSignal == 0 ) { + if( occupied->WarningSignal() == 0 ) { cue_action( driver_hint::hornon, 1 ); // low tone horn by default } } else { - if( occupied->WarningSignal != 0 ) { + if( occupied->WarningSignal() != 0 ) { cue_action( driver_hint::hornoff ); // a tu się kończy } } @@ -365,9 +365,9 @@ TController::control_security_system( double const Timedelta ) { } } // basic emergency stop handling, while at it - if( true == occupied->RadioStopFlag // radio-stop + if( true == occupied->RadioStopFlag() // radio-stop && occupied->Vel < 0.01 // and actual stop - && true == occupied->Radio ) { // and we didn't touch the radio yet + && true == occupied->Radio() ) { // and we didn't touch the radio yet // turning off the radio should reset the flag, during security system check if( m_radiocontroltime > 5.0 ) { // arbitrary delay between stop and disabling the radio cue_action( driver_hint::radiooff ); @@ -377,17 +377,17 @@ TController::control_security_system( double const Timedelta ) { } } if( iEngineActive - && ( false == occupied->Radio || false == occupied->RadioFuse ) - && false == occupied->RadioStopFlag ) { + && ( false == occupied->Radio() || false == occupied->RadioFuse() ) + && false == occupied->RadioStopFlag() ) { // otherwise if it's safe to do so, turn the radio back on // arbitrary 5 sec delay before switching radio back on m_radiocontroltime = std::min( m_radiocontroltime, 5.0 ); if( m_radiocontroltime < 0.0 ) { // hint at whichever of the two is open, the radio's switch or the cut-off in its power supply - if( false == occupied->RadioFuse ) { + if( false == occupied->RadioFuse() ) { cue_action( driver_hint::radiofuseon ); } - if( false == occupied->Radio ) { + if( false == occupied->Radio() ) { cue_action( driver_hint::radioon ); } } @@ -454,14 +454,14 @@ TController::sync_lights_selector() { auto const *headvehicle { pVehicles[ VehicleEnd::front ] }; if( headvehicle == nullptr ) { return; } // same choice of the light table as in TDynamicObject::SetLights() - auto const lightstable { ( occupied->CabOccupied * pVehicle->DirectionGet() >= 0 ? VehicleEnd::front : VehicleEnd::rear ) }; + auto const lightstable { ( occupied->CabOccupied() * pVehicle->DirectionGet() >= 0 ? VehicleEnd::front : VehicleEnd::rear ) }; // same choice of the lit vehicle end as in TDynamicObject::RaLightsSet() auto const headend { ( headvehicle->iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear ) }; auto const position { handover::light_selector_position( *occupied, NumberOf( lightstable ), headvehicle->physics->iLights[ headend ], headvehicle->LightList( headend ) ) }; - if( position == occupied->LightsPos ) { return; } + if( position == occupied->LightsPos() ) { return; } - occupied->LightsPos = position; + occupied->SetLightsPos(position); // visual feedback auto *train { simulation::Trains.find( pVehicle->name() ) }; if( train != nullptr ) { @@ -483,8 +483,8 @@ TController::sync_lights_dimmer() { && ( headvehicle->physics->iLights[ headend ] & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) != 0 }; auto const position { handover::dimmer_position( *occupied, headlightson ) }; - if( position != occupied->modernDimmerPosition ) { - occupied->modernDimmerPosition = position; + if( position != occupied->DimmerPosition() ) { + occupied->SetDimmerPosition(position); // visual feedback auto *train { simulation::Trains.find( pVehicle->name() ) }; if( train != nullptr ) { diff --git a/vehicle/cab/auxiliarycommands.cpp b/vehicle/cab/auxiliarycommands.cpp index a815257f4..b51faac1a 100644 --- a/vehicle/cab/auxiliarycommands.cpp +++ b/vehicle/cab/auxiliarycommands.cpp @@ -1304,5 +1304,5 @@ void TTrain::OnCommand_coolingfanstoggle(TTrain *Train, command_data const &Comm return; } - Train->controlled->RVentForceOn = !Train->controlled->RVentForceOn; + Train->controlled->SetRVentForceOn(!Train->controlled->RVentForceOn()); } diff --git a/vehicle/cab/brakecommands.cpp b/vehicle/cab/brakecommands.cpp index de4bac186..1528887c9 100644 --- a/vehicle/cab/brakecommands.cpp +++ b/vehicle/cab/brakecommands.cpp @@ -59,7 +59,7 @@ void TTrain::OnCommand_independentbrakeincrease(TTrain *Train, command_data cons auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; if (Train->occupied->brakes.config.localKind != TLocalBrake::ManualBrake) { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->MainCtrlPos > 0) + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->MainCtrlPos() > 0) { OnCommand_mastercontrollerdecrease(Train, Command); } @@ -85,7 +85,7 @@ void TTrain::OnCommand_independentbrakeincreasefast(TTrain *Train, command_data auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; if (Train->occupied->brakes.config.localKind != TLocalBrake::ManualBrake) { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->MainCtrlPos > 0) + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->MainCtrlPos() > 0) { OnCommand_mastercontrollerdecreasefast(Train, Command); } @@ -404,7 +404,7 @@ void TTrain::OnCommand_trainbrakeemergency(TTrain *Train, command_data const &Co /* if( Train->occupied->BrakeCtrlPosNo <= 0.1 ) { // hamulec bezpieczeństwa dla wagonów - Train->occupied->RadioStopFlag = true; + Train->occupied->SetRadioStopFlag(true); } */ } @@ -925,17 +925,17 @@ void TTrain::OnCommand_mubrakingindicatortoggle(TTrain *Train, command_data cons if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->controlled->Signalling) + if (false == Train->controlled->Signalling()) { // turn on - Train->controlled->Signalling = true; + Train->controlled->SetSignalling(true); // visual feedback Train->ggSignallingButton.UpdateValue(1.0, Train->dsbSwitch); } else { // turn off - Train->controlled->Signalling = false; + Train->controlled->SetSignalling(false); // visual feedback Train->ggSignallingButton.UpdateValue(0.0, Train->dsbSwitch); } diff --git a/vehicle/cab/cabcommands.cpp b/vehicle/cab/cabcommands.cpp index 8db842f8c..d0be85a5e 100644 --- a/vehicle/cab/cabcommands.cpp +++ b/vehicle/cab/cabcommands.cpp @@ -51,24 +51,24 @@ void TTrain::OnCommand_wiperswitchincrease(TTrain *Train, command_data const &Co { if (Command.action == GLFW_PRESS) { - Train->occupied->wiperSwitchPos++; - if (Train->occupied->wiperSwitchPos > Train->occupied->WiperListSize - 1) - Train->occupied->wiperSwitchPos = Train->occupied->WiperListSize - 1; + Train->occupied->SetWiperSwitchPos(Train->occupied->WiperSwitchPos() + 1); + if (Train->occupied->WiperSwitchPos() > Train->occupied->WiperListSize - 1) + Train->occupied->SetWiperSwitchPos(Train->occupied->WiperListSize - 1); // Visual feedback - Train->ggWiperSw.UpdateValue(static_cast(Train->occupied->wiperSwitchPos), Train->dsbSwitch); + Train->ggWiperSw.UpdateValue(static_cast(Train->occupied->WiperSwitchPos()), Train->dsbSwitch); } } void TTrain::OnCommand_wiperswitchdecrease(TTrain *Train, command_data const &Command) { if (Command.action == GLFW_PRESS) { - Train->occupied->wiperSwitchPos--; - if (Train->occupied->wiperSwitchPos < 0) - Train->occupied->wiperSwitchPos = 0; + Train->occupied->SetWiperSwitchPos(Train->occupied->WiperSwitchPos() - 1); + if (Train->occupied->WiperSwitchPos() < 0) + Train->occupied->SetWiperSwitchPos(0); // visual feedback - Train->ggWiperSw.UpdateValue(static_cast(Train->occupied->wiperSwitchPos), Train->dsbSwitch); + Train->ggWiperSw.UpdateValue(static_cast(Train->occupied->WiperSwitchPos()), Train->dsbSwitch); } } @@ -560,7 +560,7 @@ void TTrain::OnCommand_cabchangeforward(TTrain *Train, command_data const &Comma { // przejscie do nastepnego pojazdu auto *targetvehicle = exitdirection == VehicleEnd::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); - targetvehicle->physics->CabOccupied = Train->occupied->Neighbours[exitdirection].vehicle_end ? -1 : 1; + targetvehicle->physics->SetCabOccupied(Train->occupied->Neighbours[exitdirection].vehicle_end ? -1 : 1); Train->MoveToVehicle(targetvehicle); } } @@ -590,7 +590,7 @@ void TTrain::OnCommand_cabchangebackward(TTrain *Train, command_data const &Comm { // przejscie do nastepnego pojazdu auto *targetvehicle = exitdirection == VehicleEnd::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); - targetvehicle->physics->CabOccupied = Train->occupied->Neighbours[exitdirection].vehicle_end ? -1 : 1; + targetvehicle->physics->SetCabOccupied(Train->occupied->Neighbours[exitdirection].vehicle_end ? -1 : 1); Train->MoveToVehicle(targetvehicle); } } diff --git a/vehicle/cab/controllercommands.cpp b/vehicle/cab/controllercommands.cpp index 3126ee91c..a25bc797e 100644 --- a/vehicle/cab/controllercommands.cpp +++ b/vehicle/cab/controllercommands.cpp @@ -365,7 +365,7 @@ void TTrain::OnCommand_secondcontrollerincrease(TTrain *Train, command_data cons { if (Command.action != GLFW_RELEASE) { - Train->controlled->AnPos = std::clamp(Train->controlled->AnPos + 0.025, 0.0, 1.0); + Train->controlled->SetAnPos(std::clamp(Train->controlled->AnPos() + 0.025, 0.0, 1.0)); } } else @@ -396,7 +396,7 @@ void TTrain::OnCommand_secondcontrollerincrease(TTrain *Train, command_data cons Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); } // potentially animate tempomat button, unless the cruise control has its own - if (Train->ggScndCtrlButton.is_push() && Train->controlled->ScndCtrlPos <= 1 && false == Train->controlled->IsSpeedCtrlSeparate()) + if (Train->ggScndCtrlButton.is_push() && Train->controlled->ScndCtrlPos() <= 1 && false == Train->controlled->IsSpeedCtrlSeparate()) { Train->ggScndCtrlButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); } @@ -411,7 +411,7 @@ void TTrain::OnCommand_secondcontrollerincreasefast(TTrain *Train, command_data // on press or hold if (Train->controlled->EngineType == TEngineType::DieselElectric && true == Train->controlled->ShuntMode) { - Train->controlled->AnPos = 1.0; + Train->controlled->SetAnPos(1.0); } else { @@ -572,7 +572,7 @@ void TTrain::OnCommand_secondcontrollerdecrease(TTrain *Train, command_data cons { if (Command.action != GLFW_RELEASE) { - Train->controlled->AnPos = std::clamp(Train->controlled->AnPos - 0.025, 0.0, 1.0); + Train->controlled->SetAnPos(std::clamp(Train->controlled->AnPos() - 0.025, 0.0, 1.0)); } } else @@ -604,7 +604,7 @@ void TTrain::OnCommand_secondcontrollerdecrease(TTrain *Train, command_data cons Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); } // potentially animate tempomat button, unless the cruise control has its own - if (Train->ggScndCtrlButton.is_push() && Train->controlled->ScndCtrlPos <= 1 && false == Train->controlled->IsSpeedCtrlSeparate()) + if (Train->ggScndCtrlButton.is_push() && Train->controlled->ScndCtrlPos() <= 1 && false == Train->controlled->IsSpeedCtrlSeparate()) { if (Train->m_controlmapper.contains("tempomatoff_sw:")) { @@ -626,7 +626,7 @@ void TTrain::OnCommand_secondcontrollerdecreasefast(TTrain *Train, command_data // on press or hold if (Train->controlled->EngineType == TEngineType::DieselElectric && true == Train->controlled->ShuntMode) { - Train->controlled->AnPos = 0.0; + Train->controlled->SetAnPos(0.0); } else { @@ -643,8 +643,8 @@ void TTrain::OnCommand_secondcontrollerset(TTrain *Train, command_data const &Co if (Train->ggScndCtrl.is_push()) { auto const activeposition{Train->ggScndCtrl.is_toggle() ? - (targetposition < Train->controlled->ScndCtrlPos ? 0.f : - targetposition > Train->controlled->ScndCtrlPos ? 1.f : + (targetposition < Train->controlled->ScndCtrlPos() ? 0.f : + targetposition > Train->controlled->ScndCtrlPos() ? 1.f : Train->ggScndCtrl.GetDesiredValue()) : // leave the control in its current position if it hits the limit targetposition == 0 ? 0.f : 1.f}; diff --git a/vehicle/cab/doorcommands.cpp b/vehicle/cab/doorcommands.cpp index f801ad1dd..b5ed6b276 100644 --- a/vehicle/cab/doorcommands.cpp +++ b/vehicle/cab/doorcommands.cpp @@ -681,14 +681,14 @@ void TTrain::OnCommand_mirrorstoggle(TTrain *Train, command_data const &Command) } // only reacting to press, so the sound can loop uninterrupted - if (false == Train->occupied->MirrorForbidden) + if (false == Train->occupied->MirrorForbidden()) { // turn on - Train->occupied->MirrorForbidden = true; + Train->occupied->SetMirrorForbidden(true); } else { // turn off - Train->occupied->MirrorForbidden = false; + Train->occupied->SetMirrorForbidden(false); } } diff --git a/vehicle/cab/equipmentcommands.cpp b/vehicle/cab/equipmentcommands.cpp index c1d974872..c1c73a5c7 100644 --- a/vehicle/cab/equipmentcommands.cpp +++ b/vehicle/cab/equipmentcommands.cpp @@ -412,9 +412,9 @@ void TTrain::OnCommand_inverterenable(TTrain *Train, command_data const &Command if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->occupied->CabOccupied > 0; + bool kier = Train->DynamicObject->DirectionGet() * Train->occupied->CabOccupied() > 0; auto const flag{CouplingSet::FromBits(Train->DynamicObject->physics->inductionMotor.inverterControlCouplings)}; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->occupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->occupied->CabOccupied() < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); while (p) { if (p->physics->inductionMotor.traction.maxPower > 1) @@ -451,9 +451,9 @@ void TTrain::OnCommand_inverterdisable(TTrain *Train, command_data const &Comman if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->occupied->CabOccupied > 0; + bool kier = Train->DynamicObject->DirectionGet() * Train->occupied->CabOccupied() > 0; auto const flag{CouplingSet::FromBits(Train->DynamicObject->physics->inductionMotor.inverterControlCouplings)}; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->occupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->occupied->CabOccupied() < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); while (p) { if (p->physics->inductionMotor.traction.maxPower > 1) @@ -490,9 +490,9 @@ void TTrain::OnCommand_invertertoggle(TTrain *Train, command_data const &Command if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->occupied->CabOccupied > 0; + bool kier = Train->DynamicObject->DirectionGet() * Train->occupied->CabOccupied() > 0; auto const flag{CouplingSet::FromBits(Train->DynamicObject->physics->inductionMotor.inverterControlCouplings)}; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->occupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->occupied->CabOccupied() < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); while (p) { if (p->physics->inductionMotor.traction.maxPower > 1) diff --git a/vehicle/cab/lightcommands.cpp b/vehicle/cab/lightcommands.cpp index b8125cb40..b432ee575 100644 --- a/vehicle/cab/lightcommands.cpp +++ b/vehicle/cab/lightcommands.cpp @@ -51,7 +51,7 @@ http://mozilla.org/MPL/2.0/. // the cab light switch (cablight_sw:) is bound to the light state and follows it by itself void TTrain::set_cab_light_from_lights_preset() { - auto const cablight{occupied->LightsPresetCabLight(occupied->LightsPos)}; + auto const cablight{occupied->LightsPresetCabLight(occupied->LightsPos())}; if (false == cablight.has_value()) { return; @@ -94,11 +94,11 @@ void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data cons return; } - if (Train->occupied->LightsPos < Train->occupied->LightsPosNo || true == Train->occupied->LightsWrap) + if (Train->occupied->LightsPos() < Train->occupied->LightsPosNo || true == Train->occupied->LightsWrap) { // active light preset is stored as value in range 1-LigthPosNo - auto const restartcycle{Train->occupied->LightsPos >= Train->occupied->LightsPosNo}; - Train->occupied->LightsPos = false == restartcycle ? Train->occupied->LightsPos + 1 : 1; // wrap mode + auto const restartcycle{Train->occupied->LightsPos() >= Train->occupied->LightsPosNo}; + Train->occupied->SetLightsPos(false == restartcycle ? Train->occupied->LightsPos() + 1 : 1); // wrap mode Train->Dynamic()->SetLights(); Train->set_cab_light_from_lights_preset(); @@ -107,13 +107,13 @@ void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data cons { if (false == restartcycle) { - Train->ggLightsButton.UpdateValue(static_cast(Train->occupied->LightsPos - 1), Train->dsbSwitch); + Train->ggLightsButton.UpdateValue(static_cast(Train->occupied->LightsPos() - 1), Train->dsbSwitch); } else { // 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->occupied->LightsPos - 1), true, Train->occupied->LightsPosNo, Train->dsbSwitch); + Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->occupied->LightsPos() - 1), true, Train->occupied->LightsPosNo, Train->dsbSwitch); } } } @@ -133,11 +133,11 @@ void TTrain::OnCommand_lightspresetactivateprevious(TTrain *Train, command_data return; } - if (Train->occupied->LightsPos > 1 || true == Train->occupied->LightsWrap) + if (Train->occupied->LightsPos() > 1 || true == Train->occupied->LightsWrap) { // active light preset is stored as value in range 1-LigthPosNo - auto const restartcycle{Train->occupied->LightsPos <= 1}; - Train->occupied->LightsPos = false == restartcycle ? Train->occupied->LightsPos - 1 : Train->occupied->LightsPosNo; // wrap mode + auto const restartcycle{Train->occupied->LightsPos() <= 1}; + Train->occupied->SetLightsPos(false == restartcycle ? Train->occupied->LightsPos() - 1 : Train->occupied->LightsPosNo); // wrap mode Train->Dynamic()->SetLights(); Train->set_cab_light_from_lights_preset(); @@ -146,12 +146,12 @@ void TTrain::OnCommand_lightspresetactivateprevious(TTrain *Train, command_data { if (false == restartcycle) { - Train->ggLightsButton.UpdateValue(static_cast(Train->occupied->LightsPos - 1), Train->dsbSwitch); + Train->ggLightsButton.UpdateValue(static_cast(Train->occupied->LightsPos() - 1), Train->dsbSwitch); } else { // back past the first position to the last one, the same way (eu07/maszyna#464) - Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->occupied->LightsPos - 1), false, Train->occupied->LightsPosNo, Train->dsbSwitch); + Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->occupied->LightsPos() - 1), false, Train->occupied->LightsPosNo, Train->dsbSwitch); } } } @@ -205,7 +205,7 @@ void TTrain::OnCommand_lightsset(TTrain *Train, command_data const &Command) // set custom item in Lights inventory Train->occupied->Lights[VehicleEnd::front][17] = static_cast(Command.param1); Train->occupied->Lights[VehicleEnd::rear][17] = static_cast(Command.param2); - Train->occupied->LightsPos = 18; // nasza custom pozycja + Train->occupied->SetLightsPos(18); // nasza custom pozycja Train->Dynamic()->SetLights(); } @@ -829,7 +829,7 @@ void TTrain::OnCommand_modernlightdimmerincrease(TTrain *Train, command_data con // update modern dimmer state if (false == Train->occupied->stepDimmerPosition(1)) return; // już na maksimum i nie można cyklicznie - auto const dimPos = Train->occupied->modernDimmerPosition; + auto const dimPos = Train->occupied->DimmerPosition(); // update lightning // Train->Dynamic()->SetLights(); Train->Dynamic()->SetLightDimmings(); @@ -848,7 +848,7 @@ void TTrain::OnCommand_modernlightdimmerdecrease(TTrain *Train, command_data con { if (false == Train->occupied->stepDimmerPosition(-1)) return; // już na minimum i nie można cyklicznie - auto const dimPos = Train->occupied->modernDimmerPosition; + auto const dimPos = Train->occupied->DimmerPosition(); // Train->Dynamic()->SetLights(); Train->Dynamic()->SetLightDimmings(); @@ -1053,7 +1053,7 @@ void TTrain::OnCommand_headlightsdimtoggle(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->DynamicObject->physics->modernDimmerPosition == 0) + if (Train->DynamicObject->physics->DimmerPosition() == 0) { // turn on OnCommand_headlightsdimenable(Train, Command); @@ -1089,7 +1089,7 @@ void TTrain::OnCommand_headlightsdimenable(TTrain *Train, command_data const &Co Train->DynamicObject->DimHeadlights = true; */ - Train->DynamicObject->physics->modernDimmerPosition = Train->DynamicObject->physics->clampDimmerPosition(1); // ustawiamy modern dimmer na flage przyciemnienia + Train->DynamicObject->physics->SetDimmerPosition(Train->DynamicObject->physics->clampDimmerPosition(1)); // ustawiamy modern dimmer na flage przyciemnienia Train->DynamicObject->SetLightDimmings(); } } @@ -1115,7 +1115,7 @@ void TTrain::OnCommand_headlightsdimdisable(TTrain *Train, command_data const &C Train->DynamicObject->DimHeadlights = false; */ - Train->DynamicObject->physics->modernDimmerPosition = 0; // ustawiamy modern dimmer na flage rozjasnienia + Train->DynamicObject->physics->SetDimmerPosition(0); // ustawiamy modern dimmer na flage rozjasnienia Train->DynamicObject->SetLightDimmings(); } } diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index bc7847051..8be688c36 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -915,7 +915,7 @@ void TTrain::set_cab_controls(int const Cab) if (ggModernLightDimSw.SubModel != nullptr) { - occupied->modernDimmerPosition = occupied->modernDimmerDefaultPosition; + occupied->SetDimmerPosition(occupied->modernDimmerDefaultPosition); ggModernLightDimSw.PutValue(static_cast(occupied->modernDimmerDefaultPosition)); } @@ -1003,7 +1003,7 @@ void TTrain::set_cab_controls(int const Cab) // automatic relays (AutoRelay) ggAutoRelayButton.PutValue(occupied->AutoRelayFlag ? 1.f : 0.f); // lights - ggLightsButton.PutValue(static_cast(occupied->LightsPos - 1)); + ggLightsButton.PutValue(static_cast(occupied->LightsPos() - 1)); auto const vehicleend{cab_to_end(Cab)}; @@ -1041,9 +1041,9 @@ void TTrain::set_cab_controls(int const Cab) ggRightLightButton.PutValue(-1.f); } } - if (1 == DynamicObject->physics->modernDimmerPosition) + if (1 == DynamicObject->physics->DimmerPosition()) { - ggDimHeadlightsButton.PutValue(static_cast(DynamicObject->physics->modernDimmerPosition)); + ggDimHeadlightsButton.PutValue(static_cast(DynamicObject->physics->DimmerPosition())); } // cab lights if (true == Cabine[Cab].bLightDim) @@ -1097,7 +1097,7 @@ void TTrain::set_cab_controls(int const Cab) if (ggWiperSw.SubModel != nullptr) { - ggWiperSw.PutValue(static_cast(occupied->wiperSwitchPos)); + ggWiperSw.PutValue(static_cast(occupied->WiperSwitchPos())); } if (ggBrakeOperationModeCtrl.SubModel != nullptr) @@ -1107,7 +1107,7 @@ void TTrain::set_cab_controls(int const Cab) // alarm chain ggAlarmChain.PutValue(controlled->brakes.alarmChain ? 1.f : 0.f); // brake signalling - ggSignallingButton.PutValue(controlled->Signalling ? 1.f : 0.f); + ggSignallingButton.PutValue(controlled->Signalling() ? 1.f : 0.f); // multiple-unit current indicator source ggNextCurrentButton.PutValue(ShowNextCurrent ? 1.f : 0.f); // water pump @@ -1174,14 +1174,14 @@ void TTrain::set_cab_controls(int const Cab) ggRadioVolumeSelector.PutValue(m_radiovolume); // finding each inverter - not so optimal, but action ins performed only during changing cabin - bool kier = DynamicObject->DirectionGet() * occupied->CabOccupied > 0; + bool kier = DynamicObject->DirectionGet() * occupied->CabOccupied() > 0; auto const flag{CouplingSet::FromBits(DynamicObject->physics->inductionMotor.inverterControlCouplings)}; int itemstart = 0; for ([[maybe_unused]] auto const &item : ggInverterToggleButtons) // for each button { int itemindex = itemstart; itemstart++; - TDynamicObject *p = DynamicObject->GetFirstDynamic(occupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); + TDynamicObject *p = DynamicObject->GetFirstDynamic(occupied->CabOccupied() < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); while (p) { if (p->physics->inductionMotor.traction.maxPower > 1) @@ -1649,20 +1649,20 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con } } // TODO: move viable dedicated gauges to the automatic array - std::unordered_map const autoboolgauges = { + std::unordered_map const autoboolgauges = { {"doormode_sw:", &occupied->Doors.remote_only}, - {"coolingfans_sw:", &controlled->RVentForceOn}, + {"coolingfans_sw:", &controlled->RVentForceOn()}, {"pantfront_sw:", &pantographUnit->pantographs[VehicleEnd::front].valve.is_enabled}, {"pantrear_sw:", &pantographUnit->pantographs[VehicleEnd::rear].valve.is_enabled}, {"pantfrontoff_sw:", &pantographUnit->pantographs[VehicleEnd::front].valve.is_disabled}, {"pantrearoff_sw:", &pantographUnit->pantographs[VehicleEnd::rear].valve.is_disabled}, - {"radio_sw:", &occupied->Radio}, - {"radiofuse_sw:", &occupied->RadioFuse}, + {"radio_sw:", &occupied->Radio()}, + {"radiofuse_sw:", &occupied->RadioFuse()}, {"cablight_sw:", &Cabine[iCabn].bLight}, {"springbraketoggle_bt:", &occupied->brakes.spring.activate}, {"couplingdisconnect_sw:", &m_couplingdisconnect}, {"couplingdisconnectback_sw:", &m_couplingdisconnectback}, - {"mirrors_sw:", &occupied->MirrorForbidden}, + {"mirrors_sw:", &occupied->MirrorForbidden()}, }; { auto lookup = autoboolgauges.find(Label); @@ -2013,7 +2013,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con // shunt mode power slider auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&controlled->AnPos); + gauge.AssignDouble(&controlled->AnPos()); m_controlmapper.insert(gauge, "shuntmodepower:"); } else if (Label == "heatingvoltage:") diff --git a/vehicle/cab/signalcommands.cpp b/vehicle/cab/signalcommands.cpp index bc3c6183c..4b63558af 100644 --- a/vehicle/cab/signalcommands.cpp +++ b/vehicle/cab/signalcommands.cpp @@ -62,10 +62,10 @@ void TTrain::OnCommand_hornlowactivate(TTrain *Train, command_data const &Comman if (Command.action == GLFW_PRESS) { // only need to react to press, sound will continue until stopped - if (false == TestFlag(Train->occupied->WarningSignal, horn::low)) + if (false == TestFlag(Train->occupied->WarningSignal(), horn::low)) { // turn on - Train->occupied->WarningSignal = horn::pressed(Train->occupied->WarningSignal, horn::low, Train->has_single_horn_lever()); + Train->occupied->SetWarningSignal(horn::pressed(Train->occupied->WarningSignal(), horn::low, Train->has_single_horn_lever())); // visual feedback Train->ggHornButton.UpdateValue(-1.0); Train->ggHornLowButton.UpdateValue(1.0); @@ -74,9 +74,9 @@ void TTrain::OnCommand_hornlowactivate(TTrain *Train, command_data const &Comman else if (Command.action == GLFW_RELEASE) { // turn off - Train->occupied->WarningSignal = horn::released(Train->occupied->WarningSignal, horn::low); + Train->occupied->SetWarningSignal(horn::released(Train->occupied->WarningSignal(), horn::low)); // visual feedback - if (false == (Train->has_single_horn_lever() && TestFlag(Train->occupied->WarningSignal, horn::high))) + if (false == (Train->has_single_horn_lever() && TestFlag(Train->occupied->WarningSignal(), horn::high))) { // leave the single lever alone if it was moved to the other tone in the meantime Train->ggHornButton.UpdateValue(0.0); @@ -100,10 +100,10 @@ void TTrain::OnCommand_hornhighactivate(TTrain *Train, command_data const &Comma if (Command.action == GLFW_PRESS) { // only need to react to press, sound will continue until stopped - if (false == TestFlag(Train->occupied->WarningSignal, horn::high)) + if (false == TestFlag(Train->occupied->WarningSignal(), horn::high)) { // turn on - Train->occupied->WarningSignal = horn::pressed(Train->occupied->WarningSignal, horn::high, Train->has_single_horn_lever()); + Train->occupied->SetWarningSignal(horn::pressed(Train->occupied->WarningSignal(), horn::high, Train->has_single_horn_lever())); // visual feedback Train->ggHornButton.UpdateValue(1.0); Train->ggHornHighButton.UpdateValue(1.0); @@ -112,9 +112,9 @@ void TTrain::OnCommand_hornhighactivate(TTrain *Train, command_data const &Comma else if (Command.action == GLFW_RELEASE) { // turn off - Train->occupied->WarningSignal = horn::released(Train->occupied->WarningSignal, horn::high); + Train->occupied->SetWarningSignal(horn::released(Train->occupied->WarningSignal(), horn::high)); // visual feedback - if (false == (Train->has_single_horn_lever() && TestFlag(Train->occupied->WarningSignal, horn::low))) + if (false == (Train->has_single_horn_lever() && TestFlag(Train->occupied->WarningSignal(), horn::low))) { // leave the single lever alone if it was moved to the other tone in the meantime Train->ggHornButton.UpdateValue(0.0); @@ -138,10 +138,10 @@ void TTrain::OnCommand_whistleactivate(TTrain *Train, command_data const &Comman if (Command.action == GLFW_PRESS) { // only need to react to press, sound will continue until stopped - if (false == TestFlag(Train->occupied->WarningSignal, 4)) + if (false == TestFlag(Train->occupied->WarningSignal(), 4)) { // turn on - Train->occupied->WarningSignal |= 4; + Train->occupied->SetWarningSignal(Train->occupied->WarningSignal() | 4); // visual feedback Train->ggWhistleButton.UpdateValue(1.0); } @@ -149,7 +149,7 @@ void TTrain::OnCommand_whistleactivate(TTrain *Train, command_data const &Comman else if (Command.action == GLFW_RELEASE) { // turn off - Train->occupied->WarningSignal &= ~4; + Train->occupied->SetWarningSignal(Train->occupied->WarningSignal() & ~4); // visual feedback Train->ggWhistleButton.UpdateValue(0.0); } @@ -165,14 +165,14 @@ void TTrain::OnCommand_radiotoggle(TTrain *Train, command_data const &Command) // NOTE: works without the switch in the 3d model too, to allow system reset after receiving radio-stop signal // only reacting to press, so the sound can loop uninterrupted // NOTE: flips the state directly rather than through radioenable/radiodisable, so it doesn't move the radioon_sw:/radiooff_sw: buttons - Train->occupied->Radio = (false == Train->occupied->Radio); + Train->occupied->SetRadio((false == Train->occupied->Radio())); } void TTrain::OnCommand_radioenable(TTrain *Train, command_data const &Command) { if (Command.action == GLFW_PRESS) { - Train->occupied->Radio = true; + Train->occupied->SetRadio(true); // visual feedback if (Train->m_controlmapper.contains("radioon_sw:")) { @@ -192,7 +192,7 @@ void TTrain::OnCommand_radiodisable(TTrain *Train, command_data const &Command) { if (Command.action == GLFW_PRESS) { - Train->occupied->Radio = false; + Train->occupied->SetRadio(false); // visual feedback if (Train->m_controlmapper.contains("radiooff_sw:")) { @@ -219,14 +219,14 @@ void TTrain::OnCommand_radiofusetoggle(TTrain *Train, command_data const &Comman // NOTE: flips the state directly rather than through radiofuseenable/radiofusedisable, so it doesn't move the // radiofuseon_sw:/radiofuseoff_sw: buttons - Train->occupied->RadioFuse = (false == Train->occupied->RadioFuse); + Train->occupied->SetRadioFuse((false == Train->occupied->RadioFuse())); } void TTrain::OnCommand_radiofuseenable(TTrain *Train, command_data const &Command) { if (Command.action == GLFW_PRESS) { - Train->occupied->RadioFuse = true; + Train->occupied->SetRadioFuse(true); // visual feedback if (Train->m_controlmapper.contains("radiofuseon_sw:")) { @@ -246,7 +246,7 @@ void TTrain::OnCommand_radiofusedisable(TTrain *Train, command_data const &Comma { if (Command.action == GLFW_PRESS) { - Train->occupied->RadioFuse = false; + Train->occupied->SetRadioFuse(false); // visual feedback if (Train->m_controlmapper.contains("radiofuseoff_sw:")) { diff --git a/vehicle/cab/sounds.cpp b/vehicle/cab/sounds.cpp index 305f19c34..3e0eb2d6c 100644 --- a/vehicle/cab/sounds.cpp +++ b/vehicle/cab/sounds.cpp @@ -500,7 +500,7 @@ void TTrain::update_sounds_radio() // radiostop if (m_radiostop) { - if (true == radioenabled && true == occupied->RadioStopFlag) + if (true == radioenabled && true == occupied->RadioStopFlag()) { m_radiostop->play(sound_flags::exclusive | sound_flags::looping); radio_message_played |= true; diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 2660be874..b9731afc9 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -103,7 +103,7 @@ bool TTrain::Init(TDynamicObject *NewDynamicObject, bool e3d) ErrorLog( "Bad config: can't take control of inactive vehicle \"" + NewDynamicObject->asName + "\"" ); return false; */ - auto const activecab{(NewDynamicObject->physics->CabOccupied > 0 ? "1" : NewDynamicObject->physics->CabOccupied < 0 ? "2" : "p")}; + auto const activecab{(NewDynamicObject->physics->CabOccupied() > 0 ? "1" : NewDynamicObject->physics->CabOccupied() < 0 ? "2" : "p")}; NewDynamicObject->create_controller(activecab, NewDynamicObject->ctOwner != nullptr); } @@ -115,14 +115,14 @@ bool TTrain::Init(TDynamicObject *NewDynamicObject, bool e3d) fMainRelayTimer = 0; // Hunter, do k...y nędzy, ustawiaj wartości początkowe zmiennych! - iCabn = occupied->CabOccupied > 0 ? 1 : occupied->CabOccupied < 0 ? 2 : 0; + iCabn = occupied->CabOccupied() > 0 ? 1 : occupied->CabOccupied() < 0 ? 2 : 0; { Global.CurrentMaxTextureSize = Global.iMaxCabTextureSize; auto const filename{occupied->TypeName + ".mmd"}; LoadMMediaFile(filename); - InitializeCab(occupied->CabOccupied, filename); + InitializeCab(occupied->CabOccupied(), filename); Global.CurrentMaxTextureSize = Global.iMaxTextureSize; @@ -169,7 +169,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const } dict->insert("name", DynamicObject->asName); - dict->insert("cab", occupied->CabOccupied); + dict->insert("cab", occupied->CabOccupied()); dict->insert("cabactive", occupied->CabActive); dict->insert("master", occupied->CabMaster); // basic systems state data @@ -208,10 +208,10 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const // reverser dict->insert("direction", occupied->DirActive); // throttle - dict->insert("mainctrl_pos", controlled->MainCtrlPos); + dict->insert("mainctrl_pos", controlled->MainCtrlPos()); dict->insert("mainctrl_pos_count", controlled->MainCtrlPosNo); dict->insert("main_ctrl_actual_pos", controlled->MainCtrlActualPos); - dict->insert("scndctrl_pos", controlled->ScndCtrlPos); + dict->insert("scndctrl_pos", controlled->ScndCtrlPos()); dict->insert("dynamicbrake_pos", controlled->brakes.electrodynamic.controllerPosition); dict->insert("scnd_ctrl_actual_pos", controlled->ScndCtrlActualPos); dict->insert("brakectrl_pos", controlled->brakes.handlePositionSmooth); @@ -251,8 +251,8 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("universal" + std::to_string(idx), ggUniversals[idx].GetValue() > 0.5); } } - dict->insert("radio", occupied->Radio); - dict->insert("radio_fuse", occupied->RadioFuse); + dict->insert("radio", occupied->Radio()); + dict->insert("radio_fuse", occupied->RadioFuse()); dict->insert("radio_channel", RadioChannel()); dict->insert("radio_volume", m_radiovolume); dict->insert("door_lock", occupied->Doors.lock_enabled); @@ -314,8 +314,8 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("compressors_" + idx + "_car_no", std::get<2>(bCompressors[i])); } - bool kier = DynamicObject->DirectionGet() * occupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(occupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); + bool kier = DynamicObject->DirectionGet() * occupied->CabOccupied() > 0; + TDynamicObject *p = DynamicObject->GetFirstDynamic(occupied->CabOccupied() < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); int in = 0; while (p && in < 8) { @@ -424,10 +424,10 @@ TTrain::state_t TTrain::get_state() const btLampkaNapNastHam.GetValue(), occupied->DirActive > 0, occupied->DirActive < 0, - occupied->Doors.instances[occupied->CabOccupied < 0 ? VehicleSide::right : VehicleSide::left].open_permit, - occupied->Doors.instances[occupied->CabOccupied < 0 ? VehicleSide::right : VehicleSide::left].is_open, - occupied->Doors.instances[occupied->CabOccupied < 0 ? VehicleSide::left : VehicleSide::right].open_permit, - occupied->Doors.instances[occupied->CabOccupied < 0 ? VehicleSide::left : VehicleSide::right].is_open, + occupied->Doors.instances[occupied->CabOccupied() < 0 ? VehicleSide::right : VehicleSide::left].open_permit, + occupied->Doors.instances[occupied->CabOccupied() < 0 ? VehicleSide::right : VehicleSide::left].is_open, + occupied->Doors.instances[occupied->CabOccupied() < 0 ? VehicleSide::left : VehicleSide::right].open_permit, + occupied->Doors.instances[occupied->CabOccupied() < 0 ? VehicleSide::left : VehicleSide::right].is_open, occupied->Doors.step_enabled, occupied->lowVoltage.Is24vAvailable(), 0, @@ -448,7 +448,7 @@ void TTrain::set_master_controller(double const Position) { auto positionchange{std::min(static_cast(Position), controlled->CoupledCtrl ? controlled->MainCtrlPosNo + controlled->ScndCtrlPosNo : controlled->MainCtrlPosNo) - - (controlled->CoupledCtrl ? controlled->MainCtrlPos + controlled->ScndCtrlPos : controlled->MainCtrlPos)}; + (controlled->CoupledCtrl ? controlled->MainCtrlPos() + controlled->ScndCtrlPos() : controlled->MainCtrlPos())}; while (positionchange < 0 && true == controlled->DecMainCtrl(1)) { ++positionchange; @@ -551,12 +551,12 @@ void TTrain::UpdateCab() // Ra: przesiadka, jeśli AI zmieniło kabinę (a człon?)... if (DynamicObject->Mechanik // może nie być? && DynamicObject->Mechanik->AIControllFlag && iCabn != ( // numer kabiny (-1: kabina B) - occupied->CabOccupied == -1 ? 2 : occupied->CabOccupied)) + occupied->CabOccupied() == -1 ? 2 : occupied->CabOccupied())) { - InitializeCab(occupied->CabOccupied, occupied->TypeName + ".mmd"); + InitializeCab(occupied->CabOccupied(), occupied->TypeName + ".mmd"); } - iCabn = occupied->CabOccupied == -1 ? 2 : occupied->CabOccupied; + iCabn = occupied->CabOccupied() == -1 ? 2 : occupied->CabOccupied(); } void TTrain::add_distance(double const Distance) @@ -566,7 +566,7 @@ void TTrain::add_distance(double const Distance) if (true == meterenabled) { - m_distancecounter += static_cast(Distance * Occupied()->CabOccupied); + m_distancecounter += static_cast(Distance * Occupied()->CabOccupied()); } else { @@ -580,14 +580,14 @@ bool TTrain::CabChange(int iDirection) { // jeśli prowadzi AI albo jest w innym członie // jak AI prowadzi, to nie można mu mieszać - if (std::abs(occupied->CabOccupied + iDirection) > 1) + if (std::abs(occupied->CabOccupied() + iDirection) > 1) return false; // ewentualna zmiana pojazdu - occupied->CabOccupied += iDirection; + occupied->SetCabOccupied(occupied->CabOccupied() + iDirection); } else { // jeśli pojazd prowadzony ręcznie albo wcale (wagon) occupied->CabDeactivisationAuto(); - if (occupied->ChangeCab(iDirection) && InitializeCab(occupied->CabOccupied, occupied->TypeName + ".mmd")) + if (occupied->ChangeCab(iDirection) && InitializeCab(occupied->CabOccupied(), occupied->TypeName + ".mmd")) { // zmiana kabiny w ramach tego samego pojazdu occupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) @@ -664,10 +664,10 @@ void TTrain::MoveToVehicle(TDynamicObject *target) // tylko jeśli ręcznie prowadzony // jeśli prowadzi AI, to mu nie robimy dywersji! Occupied()->CabDeactivisation(); - Occupied()->CabOccupied = 0; + Occupied()->SetCabOccupied(0); Occupied()->BrakeLevelSet(Occupied()->brakes.driverValve->GetPos(bh_NP)); // rozwala sterowanie hamulcem GF 04-2016 - Occupied()->MainCtrlPos = Occupied()->MainCtrlNoPowerPos(); - Occupied()->ScndCtrlPos = 0; + Occupied()->SetMainCtrlPos(Occupied()->MainCtrlNoPowerPos()); + Occupied()->SetScndCtrlPos(0); Dynamic()->MechInside = false; Dynamic()->Controller = AIdriver; @@ -722,10 +722,10 @@ void TTrain::MoveToVehicle(TDynamicObject *target) // jeśli prowadzi AI, to mu nie robimy dywersji! Occupied()->CabDeactivisation(); - Occupied()->CabOccupied = 0; + Occupied()->SetCabOccupied(0); Occupied()->BrakeLevelSet(Occupied()->brakes.driverValve->GetPos(bh_NP)); // rozwala sterowanie hamulcem GF 04-2016 - Occupied()->MainCtrlPos = Occupied()->MainCtrlNoPowerPos(); - Occupied()->ScndCtrlPos = 0; + Occupied()->SetMainCtrlPos(Occupied()->MainCtrlNoPowerPos()); + Occupied()->SetScndCtrlPos(0); Dynamic()->MechInside = false; Dynamic()->Controller = AIdriver; diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index ff508079e..12e854beb 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -304,11 +304,11 @@ void TTrain::returnMasterController(double const Deltatime) if (m_mastercontrollerreturndelay < 0.f) { m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; - if (occupied->MainCtrlPos > occupied->MainCtrlActualPos) + if (occupied->MainCtrlPos() > occupied->MainCtrlActualPos) { occupied->DecMainCtrl(1); } - else if (occupied->MainCtrlPos < occupied->MainCtrlActualPos) + else if (occupied->MainCtrlPos() < occupied->MainCtrlActualPos) { // Ra 15-01: a to nie miało być tylko cofanie? occupied->IncMainCtrl(1); @@ -419,8 +419,8 @@ void TTrain::resetUnitStates() // reads the states of the vehicles and the units in multiple, from the cab along the control coupling void TTrain::updateUnitStates() { - bool kier = DynamicObject->DirectionGet() * occupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(occupied->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); + bool kier = DynamicObject->DirectionGet() * occupied->CabOccupied() > 0; + TDynamicObject *p = DynamicObject->GetFirstDynamic(occupied->CabOccupied() < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); int in = 0; fEIMParams[0][6] = 0; iCarNo = 0; @@ -497,9 +497,9 @@ void TTrain::updateUnitStates() { fDieselParams[1 + in][0] = static_cast(p->physics->enrot * 60); fDieselParams[1 + in][1] = static_cast(p->physics->nrot); - fDieselParams[1 + in][2] = static_cast(p->physics->RList[p->physics->MainCtrlPos].R); + fDieselParams[1 + in][2] = static_cast(p->physics->RList[p->physics->MainCtrlPos()].R); fDieselParams[1 + in][3] = static_cast(p->physics->diesel.fill); - fDieselParams[1 + in][4] = static_cast(p->physics->RList[p->physics->MainCtrlPos].Mn); + fDieselParams[1 + in][4] = static_cast(p->physics->RList[p->physics->MainCtrlPos()].Mn); fDieselParams[1 + in][5] = static_cast(p->physics->diesel.clutchPressure); fDieselParams[1 + in][6] = p->physics->diesel.heat.Twy; fDieselParams[1 + in][7] = p->physics->OilPump.pressure; @@ -635,9 +635,9 @@ void TTrain::updateSecondUnitGauges() // youBy - prad w drugim czlonie: galaz lub calosc { TDynamicObject const *tmp{nullptr}; - if (DynamicObject->NextConnected() && controlled->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied == 1) + if (DynamicObject->NextConnected() && controlled->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied() == 1) tmp = DynamicObject->NextConnected(); - if (DynamicObject->PrevConnected() && controlled->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied == -1) + if (DynamicObject->PrevConnected() && controlled->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied() == -1) tmp = DynamicObject->PrevConnected(); if (tmp && tmp->physics->Power > 0) { @@ -841,7 +841,7 @@ void TTrain::updateCircuitLamps(double const Deltatime) btLampkaStyczn.Turn(controlled->LineContactorsLampLit()); // mozna prowadzic rozruch btLampkaPrzekRozn.Turn(!controlled->protection.GroundHolds() && controlled->MainCircuitLampsEnabled()); // relay is off and needs a reset btLampkaNadmSil.Turn(controlled->FuseFlagCheck() && controlled->MainCircuitLampsEnabled()); // relay is off and needs a reset - btLampkaUkrotnienie.Turn(controlled->Couplers[controlled->CabOccupied == 1 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)); + btLampkaUkrotnienie.Turn(controlled->Couplers[controlled->CabOccupied() == 1 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)); btLampkaHamPosp.Turn(TestFlag(occupied->brakes.distributor->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania // TODO: youBy wyciągnąć flagę wysokiego stopnia btLampkaNadmWent.Turn(controlled->RventRot < 5.0 && controlled->ResistorsFlagCheck()); // hunter-121211: lampka zanikowo-pradowego wentylatorow @@ -856,20 +856,20 @@ void TTrain::updateCircuitLamps(double const Deltatime) // boczniki // Ra: w SU45 boczniki wchodzą na ScndCtrlPos, a nie na ScndCtrlActualPos // - pokićkał ktoś? - int scp = controlled->RList[controlled->MainCtrlPos].ScndAct; + int scp = controlled->RList[controlled->MainCtrlPos()].ScndAct; scp = scp == 255 ? 0 : scp; // Ra: whatta hella is this? btLampkaBoczniki.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlActualPos > 0 || scp > 0); - btLampkaBocznik1.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos > 0 || controlled->ScndCtrlActualPos > 0 || scp > 0); - btLampkaBocznik2.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos > 1 || controlled->ScndCtrlActualPos > 1 || scp > 1); - btLampkaBocznik3.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos > 2 || controlled->ScndCtrlActualPos > 2 || scp > 2); - btLampkaBocznik4.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos > 3 || controlled->ScndCtrlActualPos > 3 || scp > 3); + btLampkaBocznik1.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos() > 0 || controlled->ScndCtrlActualPos > 0 || scp > 0); + btLampkaBocznik2.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos() > 1 || controlled->ScndCtrlActualPos > 1 || scp > 1); + btLampkaBocznik3.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos() > 2 || controlled->ScndCtrlActualPos > 2 || scp > 2); + btLampkaBocznik4.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos() > 3 || controlled->ScndCtrlActualPos > 3 || scp > 3); // biegi dla motoraka btLampkaGear1.Turn(controlled->ScndCtrlActualPos == 1 && controlled->diesel.clutchState > 0); // bieg 1 btLampkaGear2.Turn(controlled->ScndCtrlActualPos == 2 && controlled->diesel.clutchState > 0); // bieg 2 btLampkaHydroLockup.Turn(controlled->torqueConverter.lockedUp); // zblokowanie skrzyni z silnikiem - if (controlled->Signalling == true) + if (controlled->Signalling() == true) { if (occupied->brakes.cylinderPressure >= 1.45f) { @@ -894,7 +894,7 @@ void TTrain::updateTrainLamps() // zależnie od typu lokomotywy case train_type::emu: { - btLampkaHamienie.Turn(controlled->brakes.cylinderPressure >= 0.2 && controlled->Signalling); + btLampkaHamienie.Turn(controlled->brakes.cylinderPressure >= 0.2 && controlled->Signalling()); break; } case train_type::et41: @@ -917,9 +917,9 @@ void TTrain::updateTrainLamps() // KURS90 btLampkaMaxSila.Turn(abs(controlled->Im) >= 350); btLampkaPrzekrMaxSila.Turn(abs(controlled->Im) >= 450); - btLampkaRadio.Turn(occupied->Radio && occupied->RadioFuse); + btLampkaRadio.Turn(occupied->Radio() && occupied->RadioFuse()); btLampkaRadioMessage.Turn(radio_message_played); - btLampkaRadioStop.Turn(occupied->Radio && occupied->RadioFuse && occupied->RadioStopFlag); + btLampkaRadioStop.Turn(occupied->Radio() && occupied->RadioFuse() && occupied->RadioStopFlag()); btLampkaHamulecReczny.Turn(occupied->brakes.handBrakePosition > 0); // NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu if (DynamicObject->Mechanik != nullptr) @@ -1091,9 +1091,9 @@ void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) { // yB - wskazniki drugiego czlonu TDynamicObject const *tmp{nullptr}; //=controlled->secondUnit; //Ra 2014-07: trzeba to jeszcze wyjąć z kabiny... // Ra 2014-07: no nie ma potrzeby szukać tego w każdej klatce - if (controlled->Couplers[1].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied > 0) + if (controlled->Couplers[1].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied() > 0) tmp = DynamicObject->NextConnected(); - if (controlled->Couplers[0].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied < 0) + if (controlled->Couplers[0].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied() < 0) tmp = DynamicObject->PrevConnected(); if (tmp) @@ -1127,7 +1127,7 @@ void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) btLampkaSprezarkaB.Turn(physics->air.compressor.IsRunning()); // mutopsitka dziala btLampkaSprezarkaBOff.Turn(false == physics->air.compressor.IsRunning()); - if (controlled->Signalling == true) + if (controlled->Signalling() == true) { if (physics->brakes.cylinderPressure >= 1.45f) { @@ -1194,8 +1194,8 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) occupied->brakes.independentPosition > 0.0 ? occupied->brakes.independentPosition * LocalBrakePosNo * -1 * brakerangemultiplier : 0.0}; ggJointCtrl.UpdateValue(negativePart < 0.0 ? static_cast(negativePart) : - controlled->CoupledCtrl ? static_cast(double(controlled->MainCtrlPos + controlled->ScndCtrlPos)) : - static_cast(double(controlled->MainCtrlPos)), + controlled->CoupledCtrl ? static_cast(double(controlled->MainCtrlPos() + controlled->ScndCtrlPos())) : + static_cast(double(controlled->MainCtrlPos())), dsbNastawnikJazdy); ggJointCtrl.Update(); } @@ -1214,11 +1214,11 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) if (controlled->CoupledCtrl) { - ggMainCtrl.UpdateValue(static_cast(double(controlled->MainCtrlPos + controlled->ScndCtrlPos)), dsbNastawnikJazdy); + ggMainCtrl.UpdateValue(static_cast(double(controlled->MainCtrlPos() + controlled->ScndCtrlPos())), dsbNastawnikJazdy); } else { - ggMainCtrl.UpdateValue(static_cast(double(controlled->MainCtrlPos)), dsbNastawnikJazdy); + ggMainCtrl.UpdateValue(static_cast(double(controlled->MainCtrlPos())), dsbNastawnikJazdy); } ggMainCtrl.Update(); } @@ -1232,7 +1232,7 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) // Ra: od byte odejmowane boolean i konwertowane potem na double? if (false == ggScndCtrl.is_push()) { - ggScndCtrl.UpdateValue(static_cast(double(controlled->ScndCtrlPos - (controlled->TrainType == train_type::et42 && controlled->brakes.electrodynamic.on))), dsbNastawnikBocz); + ggScndCtrl.UpdateValue(static_cast(double(controlled->ScndCtrlPos() - (controlled->TrainType == train_type::et42 && controlled->brakes.electrodynamic.on))), dsbNastawnikBocz); } ggScndCtrl.Update(); } diff --git a/vehicle/crew.cpp b/vehicle/crew.cpp index 8032cd750..a2d87480f 100644 --- a/vehicle/crew.cpp +++ b/vehicle/crew.cpp @@ -24,15 +24,15 @@ char lower_ascii(char const Character) { // the controllers of the vehicle to the positions giving no power, and the vehicles it controls told so void cut_power(physics::Vehicle &Vehicle) { - Vehicle.MainCtrlPos = Vehicle.MainCtrlNoPowerPos(); - Vehicle.ScndCtrlPos = 0; + Vehicle.SetMainCtrlPos(Vehicle.MainCtrlNoPowerPos()); + Vehicle.SetScndCtrlPos(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(VehicleCommand::mainController, Vehicle.MainCtrlPosForCoupled(), Vehicle.CabActive); - Vehicle.SendCtrlToNext(VehicleCommand::secondaryController, Vehicle.ScndCtrlPos, Vehicle.CabActive); + Vehicle.SendCtrlToNext(VehicleCommand::secondaryController, Vehicle.ScndCtrlPos(), Vehicle.CabActive); Vehicle.SendCtrlToNext(VehicleCommand::integratedController, 0.0, Vehicle.CabActive); } @@ -128,7 +128,7 @@ void secure(physics::Vehicle &Occupied, physics::Vehicle &Controlling) { } } Occupied.CabDeactivisation(); - Occupied.CabOccupied = 0; + Occupied.SetCabOccupied(0); } } // namespace crew diff --git a/vehicle/crewchange.cpp b/vehicle/crewchange.cpp index e509ea7cf..6b5e504ed 100644 --- a/vehicle/crewchange.cpp +++ b/vehicle/crewchange.cpp @@ -70,7 +70,7 @@ vehicle_state state_of(TDynamicObject &Vehicle) { // 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.physics->CabOccupied = Cab; + Vehicle.physics->SetCabOccupied(Cab); Vehicle.Controller = AIdriver; Vehicle.create_controller(Cab > 0 ? "1" : "2", false); } @@ -91,7 +91,7 @@ void remove_driver(TDynamicObject &Vehicle) { else { // somebody else drives the train, so only what this one held is let go handover::release_ai_controls(occupied, controlling); - occupied.CabOccupied = 0; + occupied.SetCabOccupied(0); } Vehicle.Mechanik = nullptr; auto released{0}; diff --git a/vehicle/drivingaid.cpp b/vehicle/drivingaid.cpp index 9b67d967d..d0ecb2c15 100644 --- a/vehicle/drivingaid.cpp +++ b/vehicle/drivingaid.cpp @@ -68,8 +68,8 @@ input from_vehicles(physics::Vehicle const &Vehicle, physics::Vehicle const &Con result.eimic_real = Vehicle.eimic_real; result.dynamicbrakepos = Controlling.brakes.electrodynamic.controllerPosition; result.dynamicbrakeposno = Controlling.brakes.electrodynamic.controllerPositions; - result.mainctrlpos = Controlling.MainCtrlPos; - result.scndctrlpos = Controlling.ScndCtrlPos; + result.mainctrlpos = Controlling.MainCtrlPos(); + result.scndctrlpos = Controlling.ScndCtrlPos(); result.brakectrlpos = Vehicle.brakes.handlePositionSmooth; result.localbrakepos = Vehicle.brakes.independentPosition; result.cab = Cab; diff --git a/vehicle/dynamic/animations.cpp b/vehicle/dynamic/animations.cpp index 7dfc25bc3..b994c2f02 100644 --- a/vehicle/dynamic/animations.cpp +++ b/vehicle/dynamic/animations.cpp @@ -546,8 +546,8 @@ void TDynamicObject::UpdateMirror( TAnim *pAnim ) { // only animate the mirror if it's located on the same end of the vehicle as the active cab auto const isactive { ( - physics->CabOccupied > 0 ? ( EndOf( pAnim->iNumber >> 4 ) == VehicleEnd::front ? 1.0 : 0.0 ) : - physics->CabOccupied < 0 ? ( EndOf( pAnim->iNumber >> 4 ) == VehicleEnd::rear ? 1.0 : 0.0 ) : + physics->CabOccupied() > 0 ? ( EndOf( pAnim->iNumber >> 4 ) == VehicleEnd::front ? 1.0 : 0.0 ) : + physics->CabOccupied() < 0 ? ( EndOf( pAnim->iNumber >> 4 ) == VehicleEnd::rear ? 1.0 : 0.0 ) : 0.0 ) }; if( pAnim->iNumber & 1 ) diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index 8f21dd575..6e0c52cd6 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -262,7 +262,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" return 0.0; // zerowa długość to brak pojazdu } // controller position - physics->MainCtrlPos = physics->MainCtrlNoPowerPos(); + physics->SetMainCtrlPos(physics->MainCtrlNoPowerPos()); // ustawienie pozycji hamulca physics->brakes.independentPosition = 0.0; if (driveractive) diff --git a/vehicle/dynamic/lights.cpp b/vehicle/dynamic/lights.cpp index 8479de79f..132ebcdb0 100644 --- a/vehicle/dynamic/lights.cpp +++ b/vehicle/dynamic/lights.cpp @@ -59,16 +59,16 @@ http://mozilla.org/MPL/2.0/. void TDynamicObject::SetLights() { - auto const isfrontcaboccupied { physics->CabOccupied * DirectionGet() >= 0 }; + auto const isfrontcaboccupied { physics->CabOccupied() * DirectionGet() >= 0 }; int const automaticmarkers { physics->CabActive == 0 && physics->InactiveCabFlag & activation::redmarkers ? light::redmarker_left + light::redmarker_right : 0 }; - auto const lightpos { physics->LightsPos - 1 }; + auto const lightpos { physics->LightsPos() - 1 }; ByEnd const cablights { automaticmarkers > 0 ? automaticmarkers : physics->Lights[ VehicleEnd::front ][ lightpos ], automaticmarkers > 0 ? automaticmarkers : physics->Lights[ VehicleEnd::rear ][ lightpos ] }; // the custom position keeps the lights lit at coupled ends as well - auto const ignorecouplings { physics->LightsPos == 18 }; - auto *vehicle { GetFirstDynamic( physics->CabOccupied >= 0 ? VehicleEnd::front : VehicleEnd::rear, Coupling::control ) }; + auto const ignorecouplings { physics->LightsPos() == 18 }; + auto *vehicle { GetFirstDynamic( physics->CabOccupied() >= 0 ? VehicleEnd::front : VehicleEnd::rear, Coupling::control ) }; while( vehicle != nullptr ) { // set lights on given side if there's no coupling with another vehicle, turn them off otherwise auto const iscoupled { [ vehicle, ignorecouplings ]( VehicleEnd const Side ) { diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index ee0fd0fde..8628b4b71 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -623,7 +623,7 @@ void TDynamicObject::renderHornSounds() { ( physics->Vel > 0.5 && physics->brakes.alarmChain ? physics->EmergencyBrakeWarningSignal : 0 ) - | physics->WarningSignal ) }; + | physics->WarningSignal() ) }; if( TestFlag( warningsignal, 1 ) ) { sHorn1.play( sound_flags::exclusive | sound_flags::looping ); @@ -997,8 +997,8 @@ void TDynamicObject::play_mirror_sounds( VehicleSide const Side, mirror_moves::e if( Event == mirror_moves::event::none ) { return; } // as UpdateMirror(), only the mirrors of the occupied cab move - if( physics->CabOccupied == 0 ) { return; } - auto const cabend { physics->CabOccupied > 0 ? VehicleEnd::front : VehicleEnd::rear }; + if( physics->CabOccupied() == 0 ) { return; } + auto const cabend { physics->CabOccupied() > 0 ? VehicleEnd::front : VehicleEnd::rear }; for( auto &mirror : m_mirrorsounds ) { if( mirror.placement != Side || mirror.end != cabend ) { continue; } auto &sound { Event == mirror_moves::event::unfolding ? mirror.unfold : mirror.fold }; @@ -1268,7 +1268,7 @@ TDynamicObject::powertrain_sounds::renderTurboSound( physics::Vehicle const &Veh auto const pitch_diesel{Vehicle.EngineType == TEngineType::DieselEngine || Vehicle.EngineType == TEngineType::DieselElectric ? Vehicle.enrot / Vehicle.diesel.maxRevolutions * Vehicle.diesel.fill : 1}; auto const goalpitch { std::max( 0.025, ( /*engine_volume **/ pitch_diesel + engine_turbo.m_frequencyoffset ) * engine_turbo.m_frequencyfactor ) }; auto const goalvolume { ( - Vehicle.MainCtrlPos >= Vehicle.TurboTest && Vehicle.enrot > 0.1 ? + Vehicle.MainCtrlPos() >= Vehicle.TurboTest && Vehicle.enrot > 0.1 ? std::max( 0.0, ( engine_turbo_pitch + engine_turbo.m_amplitudeoffset ) * engine_turbo.m_amplitudefactor ) : 0.0 ) }; auto const currentvolume { engine_turbo.gain() }; diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index f80d991d6..e14973129 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -329,9 +329,9 @@ void TDynamicObject::updateDriver( double const dt1 ) // (physics::ConsistBrakeBlending), over the vehicles in their order from the occupied cab void TDynamicObject::distributeInductionBraking( double const dt1 ) { - auto const forward { DirectionGet() * physics->CabOccupied > 0 }; + auto const forward { DirectionGet() * physics->CabOccupied() > 0 }; std::vector consist; - for( TDynamicObject *vehicle = GetFirstDynamic( physics->CabOccupied < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control ); vehicle != nullptr; + for( TDynamicObject *vehicle = GetFirstDynamic( physics->CabOccupied() < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control ); vehicle != nullptr; vehicle = forward ? vehicle->Next( Coupling::control ) : vehicle->Prev( Coupling::control ) ) { consist.emplace_back( vehicle->physics ); } @@ -887,7 +887,7 @@ void TDynamicObject::updateWipers( double const dt1 ) for (int i = 0; i < dWiperPos.size(); i++) // iteracja po kazdej wycieraczce { bool wipersActive; - auto const bytesum = physics->WiperList[physics->wiperSwitchPos].byteSum; + auto const bytesum = physics->WiperList[physics->WiperSwitchPos()].byteSum; // rozroznienie kabinowe if (physics->CabActive == 1) { @@ -949,7 +949,7 @@ void TDynamicObject::updateWipers( double const dt1 ) sWiperToParkPlayed = false; wiperOutTimer[i] = 0.0; wiperDirection[i] = false; - workingSwitchPos[i] = physics->wiperSwitchPos; // update configuration + workingSwitchPos[i] = physics->WiperSwitchPos(); // update configuration } } @@ -966,7 +966,7 @@ void TDynamicObject::updateMirrors( double const dt1 ) auto const mirrorright { dMirrorMoveR }; if( physics->Vel > physics->MirrorVelClose || physics->CabActive == 0 && activation::mirrors - || physics->MirrorForbidden ) { + || physics->MirrorForbidden() ) { // automatically fold mirrors when above velocity threshold if( dMirrorMoveL > 0.0 ) { dMirrorMoveL = std::max( @@ -1092,8 +1092,8 @@ void TDynamicObject::RadioStop() if( Mechanik ) { // o ile ktoś go prowadzi if( physics->SecuritySystem.radiostop_available() - && physics->Radio - && physics->RadioFuse ) { + && physics->Radio() + && physics->RadioFuse() ) { // jeśli pojazd ma RadioStop i jest on aktywny // HACK cast until math types unification glm::dvec3 pos = static_cast(vPosition); diff --git a/vehicle/dynamic/visual.cpp b/vehicle/dynamic/visual.cpp index 8e322cc02..df1326fc9 100644 --- a/vehicle/dynamic/visual.cpp +++ b/vehicle/dynamic/visual.cpp @@ -431,7 +431,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) Global.DriverFigureFollowsDirection && SingleDesk && false == Mechanik->AIControllFlag }; - auto const figure { driver_figure::shown( physics->CabOccupied, physics->DirAbsolute, followsdirection ) }; + auto const figure { driver_figure::shown( physics->CabOccupied(), physics->DirAbsolute, followsdirection ) }; btMechanik1.Turn( figure > 0 ); btMechanik2.Turn( figure < 0 ); if( figure != 0 ) { diff --git a/vehicle/enginestart.cpp b/vehicle/enginestart.cpp index 99757effa..88f3e1dfe 100644 --- a/vehicle/enginestart.cpp +++ b/vehicle/enginestart.cpp @@ -59,7 +59,7 @@ physics::Vehicle *engine(physics::Vehicle const &Occupied, physics::Vehicle &Con // the cab's own vehicle is the first one auto others{Number - 1}; // behind the cab is the rear end of a vehicle driven from its front cab, and the other way round - int const behind{NumberOf(Occupied.CabOccupied < 0 ? VehicleEnd::front : VehicleEnd::rear)}; + int const behind{NumberOf(Occupied.CabOccupied() < 0 ? VehicleEnd::front : VehicleEnd::rear)}; if (auto *found{find_along(Occupied, behind, Controlled, others)}; found != nullptr) { return found; } diff --git a/vehicle/handover.cpp b/vehicle/handover.cpp index 6a2a75dce..7361c723a 100644 --- a/vehicle/handover.cpp +++ b/vehicle/handover.cpp @@ -16,7 +16,7 @@ namespace handover { void release_ai_controls(physics::Vehicle &Occupied, physics::Vehicle &Controlling) { // the AI's hornoff action touches the horn only while the AI drives - Occupied.WarningSignal = 0; + Occupied.SetWarningSignal(0); // the AI drives the sandbox directly, bypassing the manual and automatic sanding states if (Controlling.SandDose && false == (Controlling.SandDoseManual || Controlling.SandDoseAuto)) { Controlling.Sandbox(false); @@ -33,24 +33,24 @@ int light_selector_position(physics::Vehicle const &Occupied, int const Lightsta // the selector size comes from the vehicle definition, the table holds a fixed number of positions auto const positioncount{std::min(Occupied.LightsPosNo, static_cast(std::size(Occupied.Lights[0])))}; if (positioncount <= 0 || Lightstable < 0 || Lightstable >= static_cast(std::size(Occupied.Lights))) { - return Occupied.LightsPos; + return Occupied.LightsPos(); } auto const &lights{Occupied.Lights[Lightstable]}; auto const lightsmatch{[&lights, Inventory, Headlights](int const Position) { return (lights[Position - 1] & Inventory) == Headlights; }}; - if (Occupied.LightsPos >= 1 && Occupied.LightsPos <= positioncount && lightsmatch(Occupied.LightsPos)) { - return Occupied.LightsPos; + if (Occupied.LightsPos() >= 1 && Occupied.LightsPos() <= positioncount && lightsmatch(Occupied.LightsPos())) { + return Occupied.LightsPos(); } for (auto position = 1; position <= positioncount; ++position) { if (lightsmatch(position)) { return position; } } - return Occupied.LightsPos; + return Occupied.LightsPos(); } int dimmer_position(physics::Vehicle const &Occupied, bool const Headlightson) { auto const &positions{Occupied.dimPositions}; - auto const current{Occupied.modernDimmerPosition}; + auto const current{Occupied.DimmerPosition()}; auto const count{static_cast(positions.size())}; auto const isoff{[&positions, count](int const Position) { return Position < 0 || Position >= count || positions[Position].isOff; }}; diff --git a/vehicle/mainctrlact.h b/vehicle/mainctrlact.h index 15b943de1..12cdfc959 100644 --- a/vehicle/mainctrlact.h +++ b/vehicle/mainctrlact.h @@ -26,8 +26,8 @@ inline bool follows_controller(physics::Vehicle const &Vehicle) { // nobody has checked inline float position(physics::Vehicle const &Vehicle, bool const Scaletable) { auto const controller{Scaletable && follows_controller(Vehicle)}; - auto const main{controller ? Vehicle.MainCtrlPos : Vehicle.MainCtrlActualPos}; - auto const scnd{controller ? Vehicle.ScndCtrlPos : Vehicle.ScndCtrlActualPos}; + auto const main{controller ? Vehicle.MainCtrlPos() : Vehicle.MainCtrlActualPos}; + auto const scnd{controller ? Vehicle.ScndCtrlPos() : Vehicle.ScndCtrlActualPos}; return static_cast(Vehicle.CoupledCtrl ? main + scnd : main); } diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index 41e9d0220..14d708950 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -77,7 +77,7 @@ void ui::vehicleparams_panel::draw_mini(const physics::Vehicle &physics) if (physics.air.compressor.IsRunning()) draw_infobutton(STR_C("comp.")); - if (physics.WarningSignal) + if (physics.WarningSignal()) draw_infobutton(STR_C("horn"), ImVec2(361, 11)); if (physics.iLights[VehicleEnd::front] & light::redmarker_left) @@ -167,8 +167,8 @@ void ui::vehicleparams_panel::render_contents() STR_C("Controllers:\n master: %d(%d), secondary: %s\nEngine output: %.1f, current: %.0f\nRevolutions:\n engine: %.0f, motors: %.0f\n engine fans: %.0f, motor fans: %.0f+%.0f, " "cooling fans: %.0f+%.0f"), // controllers - physics.MainCtrlPos, physics.MainCtrlActualPos, - std::string(isdieselinshuntmode ? to_string(physics.AnPos, 2) + STR(" (shunt mode)") : std::to_string(physics.ScndCtrlPos) + "(" + std::to_string(physics.ScndCtrlActualPos) + ")").c_str(), + physics.MainCtrlPos(), physics.MainCtrlActualPos, + std::string(isdieselinshuntmode ? to_string(physics.AnPos(), 2) + STR(" (shunt mode)") : std::to_string(physics.ScndCtrlPos()) + "(" + std::to_string(physics.ScndCtrlActualPos) + ")").c_str(), // engine physics.EnginePower, std::abs(physics.TrainType == train_type::emu ? physics.ShowCurrent(0) : physics.Im), // revolutions diff --git a/world/TrkFoll.cpp b/world/TrkFoll.cpp index 8013af966..79362a993 100644 --- a/world/TrkFoll.cpp +++ b/world/TrkFoll.cpp @@ -345,7 +345,7 @@ bool TTrackFollower::Move(double fDistance, bool bPrimary) { // gdy zostaje na tym samym torze (przesuwanie już nie zmienia toru) if (bPrimary) { // tylko gdy początkowe ustawienie, dodajemy eventy stania do kolejki - if (Owner->physics->CabOccupied != 0) { + if (Owner->physics->CabOccupied() != 0) { pCurrentTrack->QueueEvents( pCurrentTrack->m_events1, Owner, -1.0 ); pCurrentTrack->QueueEvents( pCurrentTrack->m_events2, Owner, -1.0 ); From 242474dd11130b56f73dba1eb167efa738206dd3 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 12:33:13 +0100 Subject: [PATCH 21/30] refactor(physics): the lights, the load and the event flags are private to the vehicle - The lights switched on at each end (iLights) are LitLights(), changed through SetLitLights(): the cab's switches, the AI's light patterns and the scenery's toggles of the end signals all go through it. - The exchange of the load, which TDynamicObject ran by setting the status, the amount and the mass itself, goes through UnloadStep(), LoadStep(), FinishLoadExchange() and AcknowledgeLoadExchange(), with the same arithmetic; the change of the kind of the load is taken once (TakeLoadTypeChange()). - The events the physics reports for the sounds to follow up are raised and cleared by name (RaiseEventFlag(), ClearEventFlag(), ClearSoundFlags()). No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- application/driveruipanels.cpp | 2 +- physics/components/body.cpp | 12 +-- physics/components/collisions.cpp | 14 +-- physics/components/commands.cpp | 8 +- physics/components/controllers.cpp | 24 ++--- physics/components/doors.cpp | 62 ++++++++----- physics/components/drive.cpp | 7 +- physics/components/electrics.cpp | 10 +-- physics/components/fizsections.cpp | 2 +- physics/components/pneumatics.cpp | 2 +- physics/components/setup.cpp | 6 +- physics/components/traction.cpp | 18 ++-- physics/vehicle.h | 45 ++++++++-- simulation/blackboxrecorder.cpp | 2 +- tests/unit/test_auxiliaries.cpp | 4 +- tests/unit/test_commands.cpp | 14 +-- tests/unit/test_loads.cpp | 44 +++++----- vehicle/ai/driver.cpp | 4 +- vehicle/ai/situation.cpp | 4 +- vehicle/cab/lightcommands.cpp | 136 ++++++++++++++--------------- vehicle/cab/setup.cpp | 10 +-- vehicle/cab/train.cpp | 12 +-- vehicle/cab/update.cpp | 22 ++--- vehicle/dynamic/lifecycle.cpp | 2 +- vehicle/dynamic/lights.cpp | 22 ++--- vehicle/dynamic/load.cpp | 29 +++--- vehicle/dynamic/movement.cpp | 2 +- vehicle/dynamic/sounds.cpp | 18 ++-- vehicle/dynamic/update.cpp | 4 +- vehicle/dynamic/vehicletable.cpp | 2 +- vehicle/dynamic/visual.cpp | 44 +++++----- widgets/vehicleparams.cpp | 10 +-- world/Event.cpp | 8 +- world/station.cpp | 12 +-- 34 files changed, 331 insertions(+), 286 deletions(-) diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index f667e43a3..ae9eebe15 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -802,7 +802,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { STR_C("Name: %s%s\nLoad: %.0f %s\nStatus: %s%s\nCouplers:\n front: %s\n rear: %s"), physics.Name.c_str(), std::string( isowned ? STR(", owned by: ") + vehicle.ctOwner->OwnerName() : "" ).c_str(), - physics.LoadAmount, + physics.LoadAmount(), physics.LoadType.name.c_str(), physics.EngineDescription( 0 ).c_str(), // TODO: put wheel flat reporting in the enginedescription() diff --git a/physics/components/body.cpp b/physics/components/body.cpp index 7a54d9e5b..145f7e141 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -73,8 +73,8 @@ physics::Vehicle::Vehicle(double VelInitial, std::string const &TypeNameInit, st WriteLog("init default physic values for " + NameInit + ", [" + TypeNameInit + "]"); // BrakeLevelSet(-2); //Pascal ustawia na 0, przestawimy na odcięcie (CHK jest jeszcze nie wczytane!) - iLights[0] = 0; - iLights[1] = 0; // światła zgaszone + litLights[0] = 0; + litLights[1] = 0; // światła zgaszone // inicjalizacja stalych for (auto &scheme : RList) @@ -410,7 +410,7 @@ void physics::Vehicle::compute_movement_(double const Deltatime) { // sprawdzanie i ewentualnie wykonywanie->kasowanie poleceń - if (LoadStatus > 0) // czas doliczamy tylko jeśli trwa (roz)ładowanie + if (loadStatus > 0) // czas doliczamy tylko jeśli trwa (roz)ładowanie LastLoadChangeTime += Deltatime; // czas (roz)ładunku RunInternalCommand(); @@ -457,7 +457,7 @@ void physics::Vehicle::compute_movement_(double const Deltatime) // automatyczny rozruch, silnik spalinowy if (Drive().UpdateEngine(*this, Deltatime)) { - SetFlag(SoundFlag, sound::relay); + SetFlag(soundFlag, sound::relay); } // TODO: gather and move current calculations to dedicated method @@ -747,7 +747,7 @@ void physics::Vehicle::ComputeMass() // Ra: na razie tak, ale nie wszędzie masy wirujące się wliczają TotalMass = Mass + Mred; - if (LoadAmount == 0) + if (loadAmount == 0) { return; } @@ -765,7 +765,7 @@ void physics::Vehicle::ComputeMass() loadtypeunitweight = lookup != simulation::Weights.end() ? lookup->second : 1000.f; // legacy default unit weight value } - TotalMass += LoadAmount * loadtypeunitweight; + TotalMass += loadAmount * loadtypeunitweight; } // ************************************************************************************************* diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index d8b34be61..b78a9010f 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -199,7 +199,7 @@ void physics::Vehicle::damage_coupler(VehicleEnd const End) } // HACK: don't break articulated couplings no matter what if (DamageFlag.Set(VehicleDamage::coupling)) - EventFlag = true; + eventFlag = true; auto const hosetorn{thiscoupler.CouplingFlag.HasAll(Coupling::brakeHose)}; if (hosetorn) @@ -248,7 +248,7 @@ collision::crush_curve physics::Vehicle::crush_curve_at(VehicleEnd const End) co double physics::Vehicle::buffer_height_at(VehicleEnd const End) const { - auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 0.0}; + auto const loadshare{maxLoad > 0.f ? loadAmount / maxLoad : 0.0}; return collision::buffer_height(Couplers[End].collision, collision_kind(), loadshare); } @@ -264,7 +264,7 @@ void physics::Vehicle::derail_in_collision(DerailReason const Reason, std::strin DerailAcceleration = 0.0; DerailSide = 0; CollisionDerail = Reason; - EventFlag = true; + eventFlag = true; MainSwitch(false, range_t::local); if (Vel < 5.0) { @@ -671,7 +671,7 @@ double physics::Vehicle::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}; + auto const loadshare{maxLoad > 0.f ? loadAmount / maxLoad : 1.0}; return derailment::loaded_centre_of_gravity(empty, Mass, loadmass, loadshare, Floor, Dim.H); } @@ -739,7 +739,7 @@ void physics::Vehicle::derail(derailment::verdict const &Verdict, derailment::ve // 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; + 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); @@ -797,7 +797,7 @@ void physics::Vehicle::Derail(DerailReason const Reason) { if (DamageFlag.Set(VehicleDamage::derailed)) { - EventFlag = true; + eventFlag = true; MainSwitch(false, range_t::local); auto const velocity{V}; @@ -861,7 +861,7 @@ void physics::Vehicle::pull_off(int const Side, double const Acceleration, std:: DerailCause = derail_motion::cause::pulled_off; DerailAcceleration = Acceleration; DerailSide = Side; - EventFlag = true; + eventFlag = true; MainSwitch(false, range_t::local); tear_brake_hoses(*this); derailment_monitor.reset(); diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index da3ffc58b..65d16f643 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -734,16 +734,16 @@ bool physics::Vehicle::RunLoadCommand(VehicleCommand const Command, double CValu { OK = false; // będzie powtarzane aż się załaduje if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist - && MaxLoad > 0 && LoadAmount < MaxLoad * (1.0 + OverLoadFactor) && Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) + && maxLoad > 0 && loadAmount < maxLoad * (1.0 + OverLoadFactor) && Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) { // ten peron/rampa auto const loadname{ToLower(std::string{Argument})}; - if (LoadAmount == 0.f) + if (loadAmount == 0.f) { AssignLoad(loadname); } OK = LoadingDone(LoadSpeed, - loadname); // zmienia LoadStatus + loadname); // zmienia loadStatus } else { @@ -755,7 +755,7 @@ bool physics::Vehicle::RunLoadCommand(VehicleCommand const Command, double CValu { OK = false; // będzie powtarzane aż się rozładuje if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist - && LoadAmount > 0 // czy jest co rozladowac? + && loadAmount > 0 // czy jest co rozladowac? && Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) { // ten peron /*mozna to rozladowac*/ diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index 778f05a25..f16a99577 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -148,7 +148,7 @@ bool physics::Vehicle::IncMainCtrlSeriesMotor(int const CtrlSpeed) /* NOTE: disabled, relay configuration was moved to compute_movement_ if( true == MaxCurrentSwitch( false )) { // wylaczanie wysokiego rozruchu - SetFlag( SoundFlag, sound::relay ); + SetFlag( soundFlag, sound::relay ); } */ if (TrainType == train_type::et42) @@ -601,7 +601,7 @@ bool physics::Vehicle::AutoRelayShuntStep(bool const ARFASI2) if (lineContactors.TimeSinceSwitch() > CtrlDelay && ARFASI2) { ++ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); + SetFlag(soundFlag, sound::shuntfield); OK = true; } } @@ -610,7 +610,7 @@ bool physics::Vehicle::AutoRelayShuntStep(bool const ARFASI2) if (lineContactors.TimeSinceSwitch() > CtrlDownDelay && TrainType != train_type::emu) { --ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); + SetFlag(soundFlag, sound::shuntfield); OK = true; } } @@ -643,7 +643,7 @@ bool physics::Vehicle::AutoRelayMainStep(bool const ARFASI) if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) { --ScndCtrlActualPos; // boczniki nie dzialaja na poz. oporowych - SetFlag(SoundFlag, sound::shuntfield); + SetFlag(soundFlag, sound::shuntfield); OK = true; } } @@ -677,7 +677,7 @@ bool physics::Vehicle::AutoRelayMainUp(bool const ARFASI) } if (RList[MainCtrlActualPos].R == 0) { - SetFlag(SoundFlag, sound::parallel | sound::loud); + SetFlag(soundFlag, sound::parallel | sound::loud); OK = true; } } @@ -727,12 +727,12 @@ bool physics::Vehicle::AutoRelayMainNotchUp() if (RList[MainCtrlActualPos].R == 0 && MainCtrlActualPos != MainCtrlPosNo) { // wejscie na bezoporowa - SetFlag(SoundFlag, sound::parallel | sound::loud); + 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); + SetFlag(soundFlag, sound::parallel); } } return OK; @@ -750,7 +750,7 @@ bool physics::Vehicle::AutoRelayMainDown() OK = true; if (RList[MainCtrlActualPos].R == 0) { - SetFlag(SoundFlag, sound::parallel); + SetFlag(soundFlag, sound::parallel); } } else if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) @@ -764,7 +764,7 @@ bool physics::Vehicle::AutoRelayMainDown() if (MainCtrlActualPos > 0 && RList[MainCtrlActualPos].R == 0) { // dzwieki schodzenia z bezoporowej} - SetFlag(SoundFlag, sound::parallel); + SetFlag(soundFlag, sound::parallel); } } return OK; @@ -784,7 +784,7 @@ bool physics::Vehicle::AutoRelayLineContactorsStep(bool const motorconnectorsoff lineContactors.Close(); MainCtrlActualPos = 1; DelayCtrlFlag = false; - SetFlag(SoundFlag, sound::relay | sound::loud); + SetFlag(soundFlag, sound::relay | sound::loud); OK = true; } } @@ -818,7 +818,7 @@ bool physics::Vehicle::CamshaftRunDown() if (ScndCtrlActualPos > 0) { --ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); + SetFlag(soundFlag, sound::shuntfield); } else { @@ -875,7 +875,7 @@ bool physics::Vehicle::CamshaftRunDownEMU() { // potem boki ++ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); + SetFlag(soundFlag, sound::shuntfield); } else { diff --git a/physics/components/doors.cpp b/physics/components/doors.cpp index 994015968..5fecf74ec 100644 --- a/physics/components/doors.cpp +++ b/physics/components/doors.cpp @@ -76,13 +76,13 @@ bool physics::Vehicle::AssignLoad(std::string const &Loadname, float const Amoun if (Loadname.empty()) { // empty the vehicle if requested - LoadTypeChange = LoadType.name != Loadname; + loadTypeChange = LoadType.name != Loadname; LoadType = load_attributes(); - LoadAmount = 0.f; + loadAmount = 0.f; return true; } // can't mix load types, at least for the time being - if (LoadAmount > 0 && LoadType.name != Loadname) + if (loadAmount > 0 && LoadType.name != Loadname) { return false; } @@ -93,13 +93,29 @@ bool physics::Vehicle::AssignLoad(std::string const &Loadname, float const Amoun // didn't find matching load configuration, this type is unsupported return false; } - LoadTypeChange = LoadType.name != Loadname; + loadTypeChange = LoadType.name != Loadname; LoadType = *loadattributes; - LoadAmount = safe_clamp(Amount, 0.f, MaxLoad); + loadAmount = safe_clamp(Amount, 0.f, maxLoad); ComputeMass(); return true; } +// a step of the exchange of the load: so much taken out, the mass with it +void physics::Vehicle::UnloadStep(float const Amount) +{ + loadStatus = 1; + loadAmount = std::max(0.f, loadAmount - Amount); + ComputeMass(); +} + +// a step of the exchange of the load: so much put in, up to the capacity, the mass with it +void physics::Vehicle::LoadStep(float const Amount) +{ + loadStatus = 2; + loadAmount = std::min(maxLoad, loadAmount + Amount); // std::max not strictly needed but, eh + ComputeMass(); +} + // ************************************************************************************************* // Q: 20160713 // Test zakończenia załadunku / rozładunku @@ -110,39 +126,39 @@ bool physics::Vehicle::LoadingDone(double const LSpeed, std::string_view Loadnam if (LSpeed == 0.0) { // zerowa prędkość zmiany, to koniec - LoadStatus = 4; + loadStatus = 4; return true; } if (Loadname.empty()) { - return LoadStatus >= 4; + return loadStatus >= 4; } if (Loadname != LoadType.name) { - return LoadStatus >= 4; + return loadStatus >= 4; } // test zakończenia załadunku/rozładunku // load exchange speed is reduced if the wagon is overloaded - auto const loadchange{static_cast(std::abs(LSpeed * LastLoadChangeTime) * (LoadAmount > MaxLoad ? 0.5 : 1.0))}; + auto const loadchange{static_cast(std::abs(LSpeed * LastLoadChangeTime) * (loadAmount > maxLoad ? 0.5 : 1.0))}; if (LSpeed < 0) { // gdy rozładunek - LoadStatus = 2; // trwa rozładunek (włączenie naliczania czasu) + loadStatus = 2; // trwa rozładunek (włączenie naliczania czasu) if (loadchange > 0) // jeśli coś przeładowano { LastLoadChangeTime = 0; // naliczony czas został zużyty - LoadAmount -= loadchange; // zmniejszenie ilości ładunku + loadAmount -= loadchange; // zmniejszenie ilości ładunku CommandIn.Value1 -= loadchange; // zmniejszenie ilości do rozładowania - if (LoadAmount <= 0 || CommandIn.Value1 <= 0) + if (loadAmount <= 0 || CommandIn.Value1 <= 0) { // pusto lub rozładowano żądaną ilość - LoadStatus = 4; // skończony rozładunek - LoadAmount = safe_clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny + loadStatus = 4; // skończony rozładunek + loadAmount = safe_clamp(loadAmount, 0.f, maxLoad); // ładunek nie może być ujemny } - if (LoadAmount == 0.f) + if (loadAmount == 0.f) { AssignLoad(""); // jak nic nie ma, to nie ma też nazwy } @@ -152,22 +168,22 @@ bool physics::Vehicle::LoadingDone(double const LSpeed, std::string_view Loadnam else if (LSpeed > 0) { // gdy załadunek - LoadStatus = 1; // trwa załadunek (włączenie naliczania czasu) + loadStatus = 1; // trwa załadunek (włączenie naliczania czasu) if (loadchange > 0) // jeśli coś przeładowano { LastLoadChangeTime = 0; // naliczony czas został zużyty - LoadAmount += loadchange; // zwiększenie ładunku + loadAmount += loadchange; // zwiększenie ładunku CommandIn.Value1 -= loadchange; - if (LoadAmount >= MaxLoad * (1.0 + OverLoadFactor) || CommandIn.Value1 <= 0) + if (loadAmount >= maxLoad * (1.0 + OverLoadFactor) || CommandIn.Value1 <= 0) { - LoadStatus = 4; // skończony załadunek - LoadAmount = std::min(static_cast(MaxLoad * (1.0 + OverLoadFactor)), LoadAmount); + loadStatus = 4; // skończony załadunek + loadAmount = std::min(static_cast(maxLoad * (1.0 + OverLoadFactor)), loadAmount); } ComputeMass(); } } - return LoadStatus >= 4; + return loadStatus >= 4; } bool physics::Vehicle::ChangeDoorPermitPreset(int const Change, range_t const Notify) @@ -231,7 +247,7 @@ void physics::Vehicle::PermitDoors_(VehicleSide const Door, bool const State) if (State && State != Doors.instances[Door].open_permit) { - SetFlag(SoundFlag, sound::doorpermit); + SetFlag(soundFlag, sound::doorpermit); } Doors.instances[Door].open_permit = State; } @@ -392,7 +408,7 @@ void physics::Vehicle::update_doors(double const Deltatime) inputs.velocity = Vel; inputs.powered = doors_powered(); inputs.multipleUnit = is_multiple_unit(); - inputs.exchangingLoad = (LoadStatus & (2 | 1)) != 0; + inputs.exchangingLoad = (loadStatus & (2 | 1)) != 0; Doors.Update(inputs, Deltatime); } diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index fc489a3a9..b160d57b0 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -272,8 +272,11 @@ public: source.SourceType != TPowerSource::CurrentCollector || voltage <= source.CollectorParameters.MaxV || false == source.CollectorParameters.OVP); // wywalanie szybkiego z powodu niewłaściwego napięcia // (a line breaker closed ahead of the pantographs holds without voltage) - vehicle.EventFlag |= true == vehicle.lineBreaker.IsClosed() && ((false == vehicle.protection.UndervoltageHolds() && false == vehicle.lineBreaker.config.pantographsRequireIt) || false == vehicle.protection.OvervoltageHolds()) && - vehicle.MainSwitch(false, vehicle.TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide + if (true == vehicle.lineBreaker.IsClosed() && ((false == vehicle.protection.UndervoltageHolds() && false == vehicle.lineBreaker.config.pantographsRequireIt) || false == vehicle.protection.OvervoltageHolds()) && + vehicle.MainSwitch(false, vehicle.TrainType == train_type::emu ? range_t::unit : range_t::local)) // TODO: check whether we need to send this EMU-wide + { + vehicle.RaiseEventFlag(); + } } bool UpdateEngine(physics::Vehicle &vehicle, double /*dt*/) const override { diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index a40ace064..ec185a5a8 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -102,7 +102,7 @@ void physics::Vehicle::UpdateBatteryVoltage(double dt) auto const converteractive{lowVoltage.Is110vAvailable() || (EngineType == DieselElectric && true == lineBreaker.IsClosed()) || (EngineType == DieselEngine && true == lineBreaker.IsClosed())}; if (lowVoltage.DrainBattery(BatteryDrain(dt, converteractive)) && MainSwitch(false) && EngineType != DieselEngine && EngineType != WheelsDriven) - EventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia + eventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia } else { @@ -149,11 +149,11 @@ double physics::Vehicle::BatteryDrainCharged(double dt, bool const converteracti sn3 = dt * 0.05; else sn3 = 0; - if (iLights[0] & 63) // 64=blachy, nie ciągną prądu //rozpisać na poszczególne żarówki... + if (litLights[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 + if (litLights[1] & 63) // 64=blachy, nie ciągną prądu sn5 = dt * 0.001; else sn5 = 0; @@ -180,11 +180,11 @@ double physics::Vehicle::BatteryDrainLow(double dt, bool const converteractive) sn3 = dt * 0.001; else sn3 = 0; - if (iLights[0] & 63) // 64=blachy, nie ciągną prądu + if (litLights[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 + if (litLights[1] & 63) // 64=blachy, nie ciągną prądu sn5 = dt * 0.0010; else sn5 = 0; diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index 0aa4ce4f6..43f86ca05 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -131,7 +131,7 @@ void physics::Vehicle::LoadFIZ_Load(std::string const &line) LoadAttributes.emplace_back(ToLower(load), minoffset); } - extract_value(MaxLoad, "MaxLoad", line, ""); + extract_value(maxLoad, "MaxLoad", line, ""); extract_value(LoadQuantity, "LoadQ", line, ""); extract_value(OverLoadFactor, "OverLoadFactor", line, ""); extract_value(LoadSpeed, "LoadSpeed", line, ""); diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 146557cf0..5ac5ccf5d 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -789,7 +789,7 @@ void physics::Vehicle::CompressorCheck(double dt) } if (step.vented) { - SetFlag(SoundFlag, sound::relay | sound::loud); + SetFlag(soundFlag, sound::relay | sound::loud); } // a compressor not driven by the engine doesn't draw power (some 5 A) from the high- or low voltage circuit yet } diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index c3c275366..7e7ca796d 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -147,18 +147,18 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) if (brakes.loadSetting > 0) { - if (LoadAmount < MaxLoad * 0.45) + if (loadAmount < maxLoad * 0.45) { IncBrakeMult(); IncBrakeMult(); DecBrakeMult(); // TODO: przeinesiono do physics.cpp - if (LoadAmount < MaxLoad * 0.35) + if (loadAmount < maxLoad * 0.35) DecBrakeMult(); } else { IncBrakeMult(); // TODO: przeinesiono do physics.cpp - if (LoadAmount >= MaxLoad * 0.55) + if (loadAmount >= maxLoad * 0.55) IncBrakeMult(); } } diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index d454b62cd..b3b6e349a 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -249,12 +249,12 @@ void physics::Vehicle::MotorFailuresCheck(double const n) if (MotorCurrent > 0) { if (FuzzyLogic(abs(n), nmax * 1.1, p_elengproblem) && MainSwitch(false)) - EventFlag = true; /*zbyt duze obroty - wywalanie wskutek ognia okreznego*/ + eventFlag = true; /*zbyt duze obroty - wywalanie wskutek ognia okreznego*/ if (DamageFlag.HasAll(VehicleDamage::engine) && FuzzyLogic(MotorCurrent, (double)ImaxLo / 10.0, p_elengproblem) && MainSwitch(false)) - EventFlag = true; /*uszkodzony silnik (uplywy)*/ + eventFlag = true; /*uszkodzony silnik (uplywy)*/ /* or FuzzyLogic(Abs(U/Mn),2*NominalVoltage,1)) then */ /*poprawic potem*/ if ((FuzzyLogic(abs(Im), Imax * 2, p_elengproblem) || FuzzyLogic(abs(n), nmax * 1.11, p_elengproblem)) && DamageFlag.Set(VehicleDamage::engine)) - EventFlag = true; + eventFlag = true; /*! dorobic grzanie oporow rozruchowych i silnika*/ } } @@ -856,7 +856,7 @@ void physics::Vehicle::ShuntFieldRelaysCheck(double const tmpV, double const Pos if (scndCtrlPos != shuntfieldstate) { - SetFlag(SoundFlag, sound::relay | sound::shuntfield); + SetFlag(soundFlag, sound::relay | sound::shuntfield); } } @@ -1428,8 +1428,8 @@ void physics::Vehicle::FuseOff(void) if (!FuseFlag) { FuseFlag = true; - EventFlag = true; - SetFlag(SoundFlag, sound::relay | sound::loud); + eventFlag = true; + SetFlag(soundFlag, sound::relay | sound::loud); } } @@ -1490,7 +1490,7 @@ bool physics::Vehicle::RelayReset(int const Relays, range_t const Notify) if (reset) { - SetFlag(SoundFlag, sound::relay | sound::loud); + SetFlag(soundFlag, sound::relay | sound::loud); } if (Notify != range_t::local) @@ -1520,9 +1520,9 @@ double physics::Vehicle::v2n(void) if (SlippingWheels) // nie ma zwiazku z predkoscia liniowa V { // McZapkie-221103: uszkodzenia kol podczas poslizgu if (deltan > dmgn && FuzzyLogic(deltan, dmgn, p_slippdmg) && DamageFlag.Set(VehicleDamage::wheelWear)) // podkucie - EventFlag = true; + eventFlag = true; if (deltan < -dmgn && FuzzyLogic(-deltan, dmgn, p_slippdmg) && DamageFlag.Set(VehicleDamage::thinWheel)) // wycieranie sie obreczy - EventFlag = true; + eventFlag = true; n = nrot; // predkosc obrotowa nie zalezy od predkosci liniowej } return n; diff --git a/physics/vehicle.h b/physics/vehicle.h index c733973c2..8c836d3db 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -862,7 +862,8 @@ class Vehicle load_attributes(std::string const &Name, float const Offsetmin) : name(Name), offset_min(Offsetmin) {} }; std::vector LoadAttributes; - float MaxLoad = 0.f; /*masa w T lub ilosc w sztukach - ladownosc*/ + float const &MaxLoad() const { return maxLoad; } /*masa w T lub ilosc w sztukach - ladownosc*/ + void SetMaxLoad(float const Value) { maxLoad = Value; } double OverLoadFactor = 0.0; /*ile razy moze byc przekroczona ladownosc*/ float LoadSpeed = 0.f; float UnLoadSpeed = 0.f; /*szybkosc na- i rozladunku jednostki/s*/ @@ -905,8 +906,13 @@ class Vehicle // (vehicle_table::update_coupler_physics()); with couplerphysics all in eu07.ini every vehicle is covered bool CouplerPhysics{false}; ByEnd Neighbours; // potential collision sources - bool EventFlag = false; /*!o true jesli cos nietypowego sie wydarzy*/ - int SoundFlag = 0; /*!o patrz stale sound_ */ + // something out of the ordinary happened (the line breaker knocked out, a derailment), for the sounds to follow up + bool EventFlag() const { return eventFlag; } + void RaiseEventFlag() { eventFlag = true; } + void ClearEventFlag() { eventFlag = false; } + // the events of the step the sounds are to follow up (sound::), cleared once they did + int SoundFlag() const { return soundFlag; } + void ClearSoundFlags() { soundFlag = 0; } 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] @@ -1073,11 +1079,27 @@ class Vehicle double eAngle = M_PI * 0.5; /*-dla wagonow*/ - float LoadAmount = 0.f; /*masa w T lub ilosc w sztukach - zaladowane*/ + float const &LoadAmount() const { return loadAmount; } /*masa w T lub ilosc w sztukach - zaladowane*/ + void SetLoadAmount(float const Value) { loadAmount = Value; } load_attributes LoadType; std::string LoadQuantity; // jednostki miary - int LoadStatus = 0; //+1=trwa rozladunek,+2=trwa zaladunek,+4=zakończono,0=zaktualizowany model - bool LoadTypeChange{false}; // indicates load type was changed + // the exchange of the load: +1 unloading, +2 loading, +4 finished, 0 the model of the load updated + int LoadStatus() const { return loadStatus; } + // a step of the exchange: so much taken out, or put in up to the capacity, and the mass with it + void UnloadStep(float Amount); + void LoadStep(float Amount); + void FinishLoadExchange() { loadStatus = 4; } + // the end of the exchange seen to, the model of the load updated + void AcknowledgeLoadExchange() { loadStatus &= 1 | 2; } + void SetLoadStatusForTest(int const Value) { loadStatus = Value; } + // the kind of the load changed, for the model of the load to follow; true once, until changed again + bool LoadTypeChange() const { return loadTypeChange; } + bool TakeLoadTypeChange() + { + auto const changed{loadTypeChange}; + loadTypeChange = false; + return changed; + } double LastLoadChangeTime = 0.0; // raz (roz)ładowania #ifdef EU07_USEOLDDOORCODE bool DoorBlocked = false; // Czy jest blokada drzwi @@ -1109,7 +1131,9 @@ class Vehicle double TotalMassxg = 0.0; /*TotalMass*g*/ int iProblem = 0; // flagi problemów z taborem, aby AI nie musiało porównywać; 0=może jechać - ByEnd iLights; // bity zapalonych świateł tutaj, żeby dało się liczyć pobór prądu + // the lights switched on at each end (light::), from which the current they draw is counted + ByEnd const &LitLights() const { return litLights; } + void SetLitLights(VehicleEnd const End, int const Lights) { litLights[End] = Lights; } // Status nowszego hebelka od przyciemniania swiatel/swiatel dlugich // 0 - swiatla wylaczone (opcja dziala tylko gdy w fiz zdefiniowano OffState w sekcji Switches; w przeciwnym wypadku pstryk startuje z wartoscia == 1 @@ -1793,6 +1817,13 @@ class Vehicle private: // the switches and the controllers the cab, the AI and the scenery change only through the operations above + float maxLoad = 0.f; + bool eventFlag = false; + int soundFlag = 0; + float loadAmount = 0.f; + int loadStatus = 0; + bool loadTypeChange{false}; + ByEnd litLights; bool signalling = false; bool radio = false; bool radioFuse = true; diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 02b3bf9dd..320c444f1 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -112,7 +112,7 @@ std::uint16_t outward_lights(TDynamicObject const *Vehicle, bool const Head) { if (Vehicle == nullptr || Vehicle->physics == nullptr) return 0; auto const along{Vehicle->iDirection > 0}; - return static_cast(Vehicle->physics->iLights[Head == along ? VehicleEnd::front : VehicleEnd::rear]); + return static_cast(Vehicle->physics->LitLights()[Head == along ? VehicleEnd::front : VehicleEnd::rear]); } // the lamps the vehicle has at that end: the driver checks a pattern against those of it there are diff --git a/tests/unit/test_auxiliaries.cpp b/tests/unit/test_auxiliaries.cpp index c8ca48ed2..2b6ad7ed8 100644 --- a/tests/unit/test_auxiliaries.cpp +++ b/tests/unit/test_auxiliaries.cpp @@ -38,8 +38,8 @@ TEST_CASE("auxiliaries: the battery drained by the lights and the pantographs' c REQUIRE(eu07.lowVoltage.BatteryVoltage() == doctest::Approx(eu07.lowVoltage.config.nominalBatteryVoltage)); scenario.act("converter off, lights on, small compressor on"); eu07.ConverterSwitch(false); - eu07.iLights[VehicleEnd::front] = 1 | 2 | 4; - eu07.iLights[VehicleEnd::rear] = 16; + eu07.SetLitLights(VehicleEnd::front, 1 | 2 | 4); + eu07.SetLitLights(VehicleEnd::rear, 16); eu07.pantographAir.SwitchCompressor(true); scenario.wait(30.0); CHECK(eu07.lowVoltage.BatteryVoltage() < 0.83 * eu07.lowVoltage.config.nominalBatteryVoltage); diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index e327ac868..ac25866b9 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -69,8 +69,8 @@ std::vector state() { {"BrakeDelayFlag", [](auto const &M) { return M.brakes.delaySetting; }}, {"SandDose", [](auto const &M) { return flag(M.SandDose); }}, {"CabSignal", [](auto const &M) { return flag(M.SecuritySystem.is_cabsignal_blinking()); }}, - {"LoadAmount", [](auto const &M) { return M.LoadAmount; }}, - {"LoadStatus", [](auto const &M) { return M.LoadStatus; }}, + {"LoadAmount", [](auto const &M) { return M.LoadAmount(); }}, + {"LoadStatus", [](auto const &M) { return M.LoadStatus(); }}, {"SpeedCtrlValue", [](auto const &M) { return M.SpeedCtrlValue; }}, {"SpeedCtrlParking", [](auto const &M) { return flag(M.SpeedCtrlUnit.Parking); }}, {"SpringBrakeActivate", [](auto const &M) { return flag(M.brakes.spring.activate); }}, @@ -508,7 +508,7 @@ TEST_CASE("commands: don't pass a coupling without the control cable") { TEST_CASE("commands: a wagon loaded and unloaded by commands, which repeat until done") { vehicle wagon{definition::fiz("3wl_v2/3wl")}; - REQUIRE(wagon->MaxLoad > 0); + REQUIRE(wagon->MaxLoad() > 0); test::trace trace{"commands/loading", state(), 100}; wagon.record(trace); @@ -517,27 +517,27 @@ TEST_CASE("commands: a wagon loaded and unloaded by commands, which repeat until trace.mark("load"); wagon->PutCommand("Load=Coal", 12, 0, wagon->Loc); wagon.run(30.0); - CHECK(wagon->LoadAmount == doctest::Approx(12.0).epsilon(0.1)); + CHECK(wagon->LoadAmount() == doctest::Approx(12.0).epsilon(0.1)); CHECK(wagon->LoadType.name == "coal"); CHECK(wagon->CommandIn.Command == VehicleCommand::none); trace.mark("unload"); wagon->PutCommand("UnLoad=Coal", 20, 0, wagon->Loc); wagon.run(200.0); - CHECK(wagon->LoadAmount == doctest::Approx(0.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(0.0)); CHECK(wagon->LoadType.name.empty()); trace.check(); } SUBCASE("a load the wagon doesn't take stays a command, not done") { wagon->PutCommand("Load=passengers", 12, 0, wagon->Loc); wagon.run(10.0); - CHECK(wagon->LoadAmount == doctest::Approx(0.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(0.0)); CHECK_FALSE(wagon->CommandIn.Command == VehicleCommand::none); } SUBCASE("away from the place of the command nothing is loaded") { wagon->PutCommand("Load=Coal", 12, 5.0, TLocation{100.0, 0.0, 0.0}); wagon.run(10.0); - CHECK(wagon->LoadAmount == doctest::Approx(0.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(0.0)); CHECK(wagon->LastLoadChangeTime == doctest::Approx(0.0)); } SUBCASE("unloading an empty wagon isn't done either") { diff --git a/tests/unit/test_loads.cpp b/tests/unit/test_loads.cpp index 228ea5f5b..123389155 100644 --- a/tests/unit/test_loads.cpp +++ b/tests/unit/test_loads.cpp @@ -26,7 +26,7 @@ TEST_CASE("loads: the pantographs of an electric vehicle set up by the amount of CHECK(et42->pantographs[VehicleEnd::front].valve.is_enabled == frontraised); CHECK(et42->pantographs[VehicleEnd::rear].valve.is_enabled == rearraised); // the load itself stays as it was - CHECK(et42->LoadAmount == doctest::Approx(0.0)); + CHECK(et42->LoadAmount() == doctest::Approx(0.0)); } // a vehicle without a current collector takes no such load vehicle wagon{definition::fiz("3wl_v2/3wl")}; @@ -37,21 +37,21 @@ TEST_CASE("loads: a load assigned, of one kind at a time, up to the vehicle's ca vehicle wagon{definition::fiz("3wl_v2/3wl")}; auto const empty{wagon->TotalMass}; REQUIRE(wagon->AssignLoad("coal", 10.f)); - CHECK(wagon->LoadTypeChange); + CHECK(wagon->LoadTypeChange()); CHECK(wagon->LoadType.name == "coal"); CHECK(wagon->TotalMass > empty); // more of the same: the amount set, not added, and no more than the vehicle takes - wagon->LoadTypeChange = false; + wagon->TakeLoadTypeChange(); REQUIRE(wagon->AssignLoad("coal", 1000.f)); - CHECK_FALSE(wagon->LoadTypeChange); - CHECK(wagon->LoadAmount == doctest::Approx(wagon->MaxLoad)); + CHECK_FALSE(wagon->LoadTypeChange()); + CHECK(wagon->LoadAmount() == doctest::Approx(wagon->MaxLoad())); // another kind can't be added to a load, nor can an unknown one be loaded CHECK_FALSE(wagon->AssignLoad("ruda", 5.f)); CHECK(wagon->LoadType.name == "coal"); // emptied, with no name REQUIRE(wagon->AssignLoad("")); - CHECK(wagon->LoadTypeChange); - CHECK(wagon->LoadAmount == doctest::Approx(0.0)); + CHECK(wagon->LoadTypeChange()); + CHECK(wagon->LoadAmount() == doctest::Approx(0.0)); CHECK(wagon->LoadType.name.empty()); CHECK_FALSE(wagon->AssignLoad("unknown", 5.f)); CHECK(wagon->AssignLoad("ruda", 5.f)); @@ -61,56 +61,56 @@ TEST_CASE("loads: the steps of loading and unloading") { // most of the game's wagons may be overloaded (OverLoadFactor), the 3WL not vehicle wagon{definition::fiz("3wl_v2/3wl").set("Load", "OverLoadFactor", 1.5)}; REQUIRE(wagon->AssignLoad("coal", 10.f)); - auto const capacity{wagon->MaxLoad * (1.0 + wagon->OverLoadFactor)}; + auto const capacity{wagon->MaxLoad() * (1.0 + wagon->OverLoadFactor)}; SUBCASE("no speed of the change: done at once") { CHECK(wagon->LoadingDone(0.0, "coal")); - CHECK(wagon->LoadStatus == 4); + CHECK(wagon->LoadStatus() == 4); } SUBCASE("no load, or another one, named: done when it was") { - wagon->LoadStatus = 1; + wagon->SetLoadStatusForTest(1); CHECK_FALSE(wagon->LoadingDone(1.0, "")); CHECK_FALSE(wagon->LoadingDone(1.0, "ruda")); - wagon->LoadStatus = 4; + wagon->SetLoadStatusForTest(4); CHECK(wagon->LoadingDone(1.0, "")); } SUBCASE("unloading, step by step, what was asked or all of it, the name going with the last of it") { wagon->CommandIn.Value1 = 4.0; // asked to unload wagon->LastLoadChangeTime = 2.0; // at 1 a second CHECK_FALSE(wagon->LoadingDone(-1.0, "coal")); - CHECK(wagon->LoadStatus == 2); - CHECK(wagon->LoadAmount == doctest::Approx(8.0)); + CHECK(wagon->LoadStatus() == 2); + CHECK(wagon->LoadAmount() == doctest::Approx(8.0)); CHECK(wagon->LastLoadChangeTime == doctest::Approx(0.0)); // nothing done since the last step CHECK_FALSE(wagon->LoadingDone(-1.0, "coal")); - CHECK(wagon->LoadAmount == doctest::Approx(8.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(8.0)); wagon->LastLoadChangeTime = 2.0; CHECK(wagon->LoadingDone(-1.0, "coal")); - CHECK(wagon->LoadAmount == doctest::Approx(6.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(6.0)); wagon->CommandIn.Value1 = 100.0; wagon->LastLoadChangeTime = 10.0; CHECK(wagon->LoadingDone(-1.0, "coal")); - CHECK(wagon->LoadAmount == doctest::Approx(0.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(0.0)); CHECK(wagon->LoadType.name.empty()); } SUBCASE("loading, step by step, up to what was asked or what the vehicle takes, slower when overloaded") { wagon->CommandIn.Value1 = 5.0; wagon->LastLoadChangeTime = 2.0; CHECK_FALSE(wagon->LoadingDone(1.0, "coal")); - CHECK(wagon->LoadStatus == 1); - CHECK(wagon->LoadAmount == doctest::Approx(12.0)); + CHECK(wagon->LoadStatus() == 1); + CHECK(wagon->LoadAmount() == doctest::Approx(12.0)); wagon->LastLoadChangeTime = 3.0; CHECK(wagon->LoadingDone(1.0, "coal")); - CHECK(wagon->LoadAmount == doctest::Approx(15.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(15.0)); wagon->CommandIn.Value1 = 1000.0; wagon->LastLoadChangeTime = 1000.0; CHECK(wagon->LoadingDone(1.0, "coal")); - CHECK(wagon->LoadAmount == doctest::Approx(capacity)); - CHECK(capacity == doctest::Approx(2.5 * wagon->MaxLoad)); + CHECK(wagon->LoadAmount() == doctest::Approx(capacity)); + CHECK(capacity == doctest::Approx(2.5 * wagon->MaxLoad())); // over the vehicle's own capacity, the change goes at half the speed wagon->CommandIn.Value1 = 1000.0; wagon->LastLoadChangeTime = 4.0; CHECK_FALSE(wagon->LoadingDone(-1.0, "coal")); - CHECK(wagon->LoadAmount == doctest::Approx(capacity - 2.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(capacity - 2.0)); } } diff --git a/vehicle/ai/driver.cpp b/vehicle/ai/driver.cpp index 11faa4ffe..056d0e7a5 100644 --- a/vehicle/ai/driver.cpp +++ b/vehicle/ai/driver.cpp @@ -419,13 +419,13 @@ void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck else { // jeśli nic nie robi OrderNext( DriverOrder::prepareEngine ); - if( pVehicle->physics->iLights[ ( occupied->CabActive < 0 ? + if( pVehicle->physics->LitLights()[ ( occupied->CabActive < 0 ? VehicleEnd::rear : VehicleEnd::front ) ] & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) // któreś ze świateł zapalone? { // od wersji 357 oczekujemy podania komend dla AI przez scenerię /* - if( pVehicle->physics->iLights[ occupied->CabActive < 0 ? VehicleEnd::rear : VehicleEnd::front ] & light::headlight_upper ) // górne światło zapalone + if( pVehicle->physics->LitLights()[ occupied->CabActive < 0 ? VehicleEnd::rear : VehicleEnd::front ] & light::headlight_upper ) // górne światło zapalone OrderNext( DriverOrder::obeyTrain ); // jazda pociągowa else OrderNext( DriverOrder::shunt ); // jazda manewrowa diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index 9d0bf70c0..ed4938226 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -458,7 +458,7 @@ TController::sync_lights_selector() { // same choice of the lit vehicle end as in TDynamicObject::RaLightsSet() auto const headend { ( headvehicle->iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear ) }; auto const position { handover::light_selector_position( - *occupied, NumberOf( lightstable ), headvehicle->physics->iLights[ headend ], headvehicle->LightList( headend ) ) }; + *occupied, NumberOf( lightstable ), headvehicle->physics->LitLights()[ headend ], headvehicle->LightList( headend ) ) }; if( position == occupied->LightsPos() ) { return; } occupied->SetLightsPos(position); @@ -480,7 +480,7 @@ TController::sync_lights_dimmer() { auto const headend { ( headvehicle != nullptr && headvehicle->iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear ) }; auto const headlightson { headvehicle != nullptr - && ( headvehicle->physics->iLights[ headend ] & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) != 0 }; + && ( headvehicle->physics->LitLights()[ headend ] & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) != 0 }; auto const position { handover::dimmer_position( *occupied, headlightson ) }; if( position != occupied->DimmerPosition() ) { diff --git a/vehicle/cab/lightcommands.cpp b/vehicle/cab/lightcommands.cpp index b432ee575..edcbcef40 100644 --- a/vehicle/cab/lightcommands.cpp +++ b/vehicle/cab/lightcommands.cpp @@ -168,7 +168,7 @@ void TTrain::OnCommand_headlighttoggleleft(TTrain *Train, command_data const &Co if (Train->ggLeftEndLightButton.SubModel != nullptr || Train->ggLeftLightButton.SubModel == nullptr) { - if ((Train->occupied->iLights[vehicleend] & light::headlight_left) == 0) + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_left) == 0) { // turn on OnCommand_headlightenableleft(Train, Command); @@ -180,13 +180,13 @@ void TTrain::OnCommand_headlighttoggleleft(TTrain *Train, command_data const &Co } } else { // if the light is controlled by 3-way switch, handle both headlight and redmarker - if ((Train->occupied->iLights[vehicleend] & light::headlight_left) == 0 && - (Train->occupied->iLights[vehicleend] & light::redmarker_left) == 0) + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_left) == 0 && + (Train->occupied->LitLights()[vehicleend] & light::redmarker_left) == 0) { // turn on OnCommand_headlightenableleft(Train, Command); } - else if (Train->occupied->iLights[vehicleend] & light::headlight_left) + else if (Train->occupied->LitLights()[vehicleend] & light::headlight_left) { // switch to red OnCommand_redmarkerenableleft(Train, Command); @@ -225,14 +225,14 @@ void TTrain::OnCommand_headlightenableleft(TTrain *Train, command_data const &Co // implementation auto const vehicleend{Train->cab_to_end()}; - if ((Train->occupied->iLights[vehicleend] & light::headlight_left) == 0) + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_left) == 0) { - Train->occupied->iLights[vehicleend] ^= light::headlight_left; + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::headlight_left)); } // if the light is controlled by 3-way switch, disable marker light if (Train->ggLeftEndLightButton.SubModel == nullptr) { - Train->occupied->iLights[vehicleend] &= ~light::redmarker_left; + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] & ~light::redmarker_left); } } } @@ -251,12 +251,12 @@ void TTrain::OnCommand_headlightdisableleft(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->occupied->iLights[vehicleend] & light::headlight_left) == 0) + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_left) == 0) { return; } // already disabled - Train->occupied->iLights[vehicleend] ^= light::headlight_left; + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::headlight_left)); // visual feedback Train->ggLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -273,7 +273,7 @@ void TTrain::OnCommand_headlighttoggleright(TTrain *Train, command_data const &C if (Train->ggRightEndLightButton.SubModel != nullptr || Train->ggRightLightButton.SubModel == nullptr) { - if ((Train->occupied->iLights[vehicleend] & light::headlight_right) == 0) + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_right) == 0) { // turn on OnCommand_headlightenableright(Train, Command); @@ -285,13 +285,13 @@ void TTrain::OnCommand_headlighttoggleright(TTrain *Train, command_data const &C } } else { // if the light is controlled by 3-way switch, handle both headlight and redmarker - if ((Train->occupied->iLights[vehicleend] & light::headlight_right) == 0 && - (Train->occupied->iLights[vehicleend] & light::redmarker_right) == 0) + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_right) == 0 && + (Train->occupied->LitLights()[vehicleend] & light::redmarker_right) == 0) { // turn on OnCommand_headlightenableright(Train, Command); } - else if (Train->occupied->iLights[vehicleend] & light::headlight_right) + else if (Train->occupied->LitLights()[vehicleend] & light::headlight_right) { // switch to red OnCommand_redmarkerenableright(Train, Command); @@ -321,14 +321,14 @@ void TTrain::OnCommand_headlightenableright(TTrain *Train, command_data const &C // implementation auto const vehicleend{Train->cab_to_end()}; - if ((Train->occupied->iLights[vehicleend] & light::headlight_right) == 0) + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_right) == 0) { - Train->occupied->iLights[vehicleend] ^= light::headlight_right; + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::headlight_right)); } // if the light is controlled by 3-way switch, disable marker light if (Train->ggRightEndLightButton.SubModel == nullptr) { - Train->occupied->iLights[vehicleend] &= ~light::redmarker_right; + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] & ~light::redmarker_right); } } } @@ -347,12 +347,12 @@ void TTrain::OnCommand_headlightdisableright(TTrain *Train, command_data const & // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->occupied->iLights[vehicleend] & light::headlight_right) == 0) + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_right) == 0) { return; } // already disabled - Train->occupied->iLights[vehicleend] ^= light::headlight_right; + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::headlight_right)); // visual feedback Train->ggRightLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -366,7 +366,7 @@ void TTrain::OnCommand_headlighttoggleupper(TTrain *Train, command_data const &C if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->occupied->iLights[vehicleend] & light::headlight_upper) == 0) + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_upper) == 0) { // turn on OnCommand_headlightenableupper(Train, Command); @@ -393,12 +393,12 @@ void TTrain::OnCommand_headlightenableupper(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->occupied->iLights[vehicleend] & light::headlight_upper) != 0) + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_upper) != 0) { return; } // already enabled - Train->occupied->iLights[vehicleend] ^= light::headlight_upper; + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::headlight_upper)); // visual feedback Train->ggUpperLightButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -418,12 +418,12 @@ void TTrain::OnCommand_headlightdisableupper(TTrain *Train, command_data const & // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->occupied->iLights[vehicleend] & light::headlight_upper) == 0) + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_upper) == 0) { return; } // already disabled - Train->occupied->iLights[vehicleend] ^= light::headlight_upper; + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::headlight_upper)); // visual feedback Train->ggUpperLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -437,7 +437,7 @@ void TTrain::OnCommand_redmarkertoggleleft(TTrain *Train, command_data const &Co // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->occupied->iLights[vehicleend] & light::redmarker_left) == 0) + if ((Train->occupied->LitLights()[vehicleend] & light::redmarker_left) == 0) { // turn on OnCommand_redmarkerenableleft(Train, Command); @@ -464,12 +464,12 @@ void TTrain::OnCommand_redmarkerenableleft(TTrain *Train, command_data const &Co // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->occupied->iLights[vehicleend] & light::redmarker_left) != 0) + if ((Train->occupied->LitLights()[vehicleend] & light::redmarker_left) != 0) { return; } // already enabled - Train->occupied->iLights[vehicleend] ^= light::redmarker_left; + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::redmarker_left)); // visual feedback if (Train->ggLeftEndLightButton.SubModel != nullptr) { @@ -481,7 +481,7 @@ void TTrain::OnCommand_redmarkerenableleft(TTrain *Train, command_data const &Co // this is crude, but for now will do Train->ggLeftLightButton.UpdateValue(-1.0, Train->dsbSwitch); // if the light is controlled by 3-way switch, disable the headlight - Train->occupied->iLights[vehicleend] &= ~light::headlight_left; + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] & ~light::headlight_left); } } } @@ -500,12 +500,12 @@ void TTrain::OnCommand_redmarkerdisableleft(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->occupied->iLights[vehicleend] & light::redmarker_left) == 0) + if ((Train->occupied->LitLights()[vehicleend] & light::redmarker_left) == 0) { return; } // already disabled - Train->occupied->iLights[vehicleend] ^= light::redmarker_left; + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::redmarker_left)); // visual feedback if (Train->ggLeftEndLightButton.SubModel != nullptr) { @@ -528,7 +528,7 @@ void TTrain::OnCommand_redmarkertoggleright(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->occupied->iLights[vehicleend] & light::redmarker_right) == 0) + if ((Train->occupied->LitLights()[vehicleend] & light::redmarker_right) == 0) { // turn on OnCommand_redmarkerenableright(Train, Command); @@ -555,12 +555,12 @@ void TTrain::OnCommand_redmarkerenableright(TTrain *Train, command_data const &C // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->occupied->iLights[vehicleend] & light::redmarker_right) != 0) + if ((Train->occupied->LitLights()[vehicleend] & light::redmarker_right) != 0) { return; } // already enabled - Train->occupied->iLights[vehicleend] ^= light::redmarker_right; + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::redmarker_right)); // visual feedback if (Train->ggRightEndLightButton.SubModel != nullptr) { @@ -572,7 +572,7 @@ void TTrain::OnCommand_redmarkerenableright(TTrain *Train, command_data const &C // this is crude, but for now will do Train->ggRightLightButton.UpdateValue(-1.0, Train->dsbSwitch); // if the light is controlled by 3-way switch, disable the headlight - Train->occupied->iLights[vehicleend] &= ~light::headlight_right; + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] & ~light::headlight_right); } } } @@ -591,12 +591,12 @@ void TTrain::OnCommand_redmarkerdisableright(TTrain *Train, command_data const & // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleend{Train->cab_to_end()}; - if ((Train->occupied->iLights[vehicleend] & light::redmarker_right) == 0) + if ((Train->occupied->LitLights()[vehicleend] & light::redmarker_right) == 0) { return; } // already disabled - Train->occupied->iLights[vehicleend] ^= light::redmarker_right; + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::redmarker_right)); // visual feedback if (Train->ggRightEndLightButton.SubModel != nullptr) { @@ -625,7 +625,7 @@ void TTrain::OnCommand_headlighttogglerearleft(TTrain *Train, command_data const // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->occupied->iLights[vehicleotherend] & light::headlight_right) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_right) == 0) { OnCommand_headlightenablerearleft(Train, Command); } @@ -648,10 +648,10 @@ void TTrain::OnCommand_headlightenablerearleft(TTrain *Train, command_data const { auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // already enabled - if ((Train->occupied->iLights[vehicleotherend] & light::headlight_right) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_right) == 0) { // turn on - Train->occupied->iLights[vehicleotherend] ^= light::headlight_right; + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::headlight_right)); // visual feedback Train->ggRearLeftLightButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -669,13 +669,13 @@ void TTrain::OnCommand_headlightdisablerearleft(TTrain *Train, command_data cons { auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // already disabled - if ((Train->occupied->iLights[vehicleotherend] & light::headlight_right) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_right) == 0) { return; } // turn off - Train->occupied->iLights[vehicleotherend] ^= light::headlight_right; + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::headlight_right)); // visual feedback Train->ggRearLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -688,7 +688,7 @@ void TTrain::OnCommand_headlighttogglerearright(TTrain *Train, command_data cons // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->occupied->iLights[vehicleotherend] & light::headlight_left) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_left) == 0) { OnCommand_headlightenablerearright(Train, Command); } @@ -712,10 +712,10 @@ void TTrain::OnCommand_headlightenablerearright(TTrain *Train, command_data cons // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; - if ((Train->occupied->iLights[vehicleotherend] & light::headlight_left) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_left) == 0) { // turn on - Train->occupied->iLights[vehicleotherend] ^= light::headlight_left; + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::headlight_left)); // visual feedback Train->ggRearRightLightButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -735,13 +735,13 @@ void TTrain::OnCommand_headlightdisablerearright(TTrain *Train, command_data con // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // already disabled - if ((Train->occupied->iLights[vehicleotherend] & light::headlight_left) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_left) == 0) { return; } // turn off - Train->occupied->iLights[vehicleotherend] ^= light::headlight_left; + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::headlight_left)); // visual feedback Train->ggRearRightLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -760,7 +760,7 @@ void TTrain::OnCommand_headlighttogglerearupper(TTrain *Train, command_data cons { // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; - if ((Train->occupied->iLights[vehicleotherend] & light::headlight_upper) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_upper) == 0) { OnCommand_headlightenablerearupper(Train, Command); } @@ -784,10 +784,10 @@ void TTrain::OnCommand_headlightenablerearupper(TTrain *Train, command_data cons { // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; - if ((Train->occupied->iLights[vehicleotherend] & light::headlight_upper) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_upper) == 0) { // turn on - Train->occupied->iLights[vehicleotherend] ^= light::headlight_upper; + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::headlight_upper)); // visual feedback Train->ggRearUpperLightButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -808,13 +808,13 @@ void TTrain::OnCommand_headlightdisablerearupper(TTrain *Train, command_data con // only reacting to press, so the switch doesn't flip back and forth if key is held down auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // already disabled? - if ((Train->occupied->iLights[vehicleotherend] & light::headlight_upper) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_upper) == 0) { return; } // turn off - Train->occupied->iLights[vehicleotherend] ^= light::headlight_upper; + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::headlight_upper)); // visual feedback Train->ggRearUpperLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -865,7 +865,7 @@ void TTrain::OnCommand_redmarkertogglerearleft(TTrain *Train, command_data const // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->occupied->iLights[vehicleotherend] & light::redmarker_right) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::redmarker_right) == 0) { OnCommand_redmarkerenablerearleft(Train, Command); } @@ -889,10 +889,10 @@ void TTrain::OnCommand_redmarkerenablerearleft(TTrain *Train, command_data const { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; - if ((Train->occupied->iLights[vehicleotherend] & light::redmarker_right) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::redmarker_right) == 0) { // turn on - Train->occupied->iLights[vehicleotherend] ^= light::redmarker_right; + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::redmarker_right)); // visual feedback Train->ggRearLeftEndLightButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -912,12 +912,12 @@ void TTrain::OnCommand_redmarkerdisablerearleft(TTrain *Train, command_data cons { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; - if ((Train->occupied->iLights[vehicleotherend] & light::redmarker_right) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::redmarker_right) == 0) { return; } // turn off - Train->occupied->iLights[vehicleotherend] ^= light::redmarker_right; + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::redmarker_right)); // visual feedback Train->ggRearLeftEndLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -937,7 +937,7 @@ void TTrain::OnCommand_redmarkertogglerearright(TTrain *Train, command_data cons // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->occupied->iLights[vehicleotherend] & light::redmarker_left) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::redmarker_left) == 0) { OnCommand_redmarkerenablerearright(Train, Command); } @@ -961,10 +961,10 @@ void TTrain::OnCommand_redmarkerenablerearright(TTrain *Train, command_data cons { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; - if ((Train->occupied->iLights[vehicleotherend] & light::redmarker_left) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::redmarker_left) == 0) { // turn on - Train->occupied->iLights[vehicleotherend] ^= light::redmarker_left; + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::redmarker_left)); // visual feedback Train->ggRearRightEndLightButton.UpdateValue(1.0, Train->dsbSwitch); } @@ -984,12 +984,12 @@ void TTrain::OnCommand_redmarkerdisablerearright(TTrain *Train, command_data con { // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; - if ((Train->occupied->iLights[vehicleotherend] & light::redmarker_left) == 0) + if ((Train->occupied->LitLights()[vehicleotherend] & light::redmarker_left) == 0) { return; } // turn off - Train->occupied->iLights[vehicleotherend] ^= light::redmarker_left; + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::redmarker_left)); // visual feedback Train->ggRearRightEndLightButton.UpdateValue(0.0, Train->dsbSwitch); } @@ -1014,10 +1014,10 @@ void TTrain::OnCommand_redmarkerstoggle(TTrain * /*Train*/, command_data const & auto const lightset{light::redmarker_left | light::redmarker_right}; - vehicle->physics->iLights[CouplNr] = - false == TestFlag(vehicle->physics->iLights[CouplNr], lightset) ? - vehicle->physics->iLights[CouplNr] |= lightset : // turn signals on - vehicle->physics->iLights[CouplNr] ^= lightset; // turn signals off + auto const end{static_cast(CouplNr)}; + auto const lit{vehicle->physics->LitLights()[end]}; + vehicle->physics->SetLitLights(end, false == TestFlag(lit, lightset) ? lit | lightset : // turn signals on + lit ^ lightset); // turn signals off } } @@ -1039,10 +1039,10 @@ void TTrain::OnCommand_endsignalstoggle(TTrain * /*Train*/, command_data const & auto const lightset{light::rearendsignals}; - vehicle->physics->iLights[CouplNr] = - false == TestFlag(vehicle->physics->iLights[CouplNr], lightset) ? - vehicle->physics->iLights[CouplNr] |= lightset : // turn signals on - vehicle->physics->iLights[CouplNr] ^= lightset; // turn signals off + auto const end{static_cast(CouplNr)}; + auto const lit{vehicle->physics->LitLights()[end]}; + vehicle->physics->SetLitLights(end, false == TestFlag(lit, lightset) ? lit | lightset : // turn signals on + lit ^ lightset); // turn signals off } } diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index 8be688c36..65a9be482 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -1007,19 +1007,19 @@ void TTrain::set_cab_controls(int const Cab) auto const vehicleend{cab_to_end(Cab)}; - if ((occupied->iLights[vehicleend] & light::headlight_left) != 0) + if ((occupied->LitLights()[vehicleend] & light::headlight_left) != 0) { ggLeftLightButton.PutValue(1.f); } - if ((occupied->iLights[vehicleend] & light::headlight_right) != 0) + if ((occupied->LitLights()[vehicleend] & light::headlight_right) != 0) { ggRightLightButton.PutValue(1.f); } - if ((occupied->iLights[vehicleend] & light::headlight_upper) != 0) + if ((occupied->LitLights()[vehicleend] & light::headlight_upper) != 0) { ggUpperLightButton.PutValue(1.f); } - if ((occupied->iLights[vehicleend] & light::redmarker_left) != 0) + if ((occupied->LitLights()[vehicleend] & light::redmarker_left) != 0) { if (ggLeftEndLightButton.SubModel != nullptr) { @@ -1030,7 +1030,7 @@ void TTrain::set_cab_controls(int const Cab) ggLeftLightButton.PutValue(-1.f); } } - if ((occupied->iLights[vehicleend] & light::redmarker_right) != 0) + if ((occupied->LitLights()[vehicleend] & light::redmarker_right) != 0) { if (ggRightEndLightButton.SubModel != nullptr) { diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index b9731afc9..909d44531 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -181,8 +181,8 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("converter_overload", controlled->converter.IsOverloaded()); dict->insert("compress", controlled->air.compressor.IsRunning()); dict->insert("pant_compressor", pantographUnit->pantographAir.IsCompressorRunning()); - dict->insert("lights_front", occupied->iLights[VehicleEnd::front]); - dict->insert("lights_rear", occupied->iLights[VehicleEnd::rear]); + dict->insert("lights_front", occupied->LitLights()[VehicleEnd::front]); + dict->insert("lights_rear", occupied->LitLights()[VehicleEnd::rear]); dict->insert("off_from_dimmer", occupied->currentDimPosition().isOff); dict->insert("lights_compartments", occupied->CompartmentLights.is_active || occupied->CompartmentLights.is_disabled); if (Dynamic()->Mechanik) @@ -194,16 +194,16 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const auto const *rearvehicle{controller->Vehicle(traindirection >= 0 ? VehicleEnd::rear : VehicleEnd::front)}; auto const frontvehicledirection{(frontvehicle->DirectionGet() == controller->Vehicle()->DirectionGet() ? 1 : -1)}; auto const rearvehicledirection{(rearvehicle->DirectionGet() == controller->Vehicle()->DirectionGet() ? 1 : -1)}; - auto const fronttrainlights{frontvehicle->physics->iLights[frontvehicledirection * cabmodifier >= 0 ? VehicleEnd::front : VehicleEnd::rear]}; - auto const reartrainlights{rearvehicle->physics->iLights[rearvehicledirection * cabmodifier >= 0 ? VehicleEnd::rear : VehicleEnd::front]}; + auto const fronttrainlights{frontvehicle->physics->LitLights()[frontvehicledirection * cabmodifier >= 0 ? VehicleEnd::front : VehicleEnd::rear]}; + auto const reartrainlights{rearvehicle->physics->LitLights()[rearvehicledirection * cabmodifier >= 0 ? VehicleEnd::rear : VehicleEnd::front]}; dict->insert("lights_train_front", fronttrainlights); dict->insert("lights_train_rear", reartrainlights); } else { // fallback, in the unlikely case we lose the controller - dict->insert("lights_train_front", occupied->iLights[VehicleEnd::front]); - dict->insert("lights_train_rear", occupied->iLights[VehicleEnd::rear]); + dict->insert("lights_train_front", occupied->LitLights()[VehicleEnd::front]); + dict->insert("lights_train_rear", occupied->LitLights()[VehicleEnd::rear]); } // reverser dict->insert("direction", occupied->DirActive); diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 12e854beb..257b0efcc 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -966,16 +966,16 @@ void TTrain::updateTrainLamps() btLampkaSpringBrakeInactive.Turn(!occupied->brakes.spring.isActive); // light indicators // NOTE: sides are hardcoded to deal with setups where single cab is equipped with all indicators - btLampkaUpperLight.Turn((occupied->iLights[VehicleEnd::front] & light::headlight_upper) != 0); - btLampkaLeftLight.Turn((occupied->iLights[VehicleEnd::front] & light::headlight_left) != 0); - btLampkaRightLight.Turn((occupied->iLights[VehicleEnd::front] & light::headlight_right) != 0); - btLampkaLeftEndLight.Turn((occupied->iLights[VehicleEnd::front] & light::redmarker_left) != 0); - btLampkaRightEndLight.Turn((occupied->iLights[VehicleEnd::front] & light::redmarker_right) != 0); - btLampkaRearUpperLight.Turn((occupied->iLights[VehicleEnd::rear] & light::headlight_upper) != 0); - btLampkaRearLeftLight.Turn((occupied->iLights[VehicleEnd::rear] & light::headlight_left) != 0); - btLampkaRearRightLight.Turn((occupied->iLights[VehicleEnd::rear] & light::headlight_right) != 0); - btLampkaRearLeftEndLight.Turn((occupied->iLights[VehicleEnd::rear] & light::redmarker_left) != 0); - btLampkaRearRightEndLight.Turn((occupied->iLights[VehicleEnd::rear] & light::redmarker_right) != 0); + btLampkaUpperLight.Turn((occupied->LitLights()[VehicleEnd::front] & light::headlight_upper) != 0); + btLampkaLeftLight.Turn((occupied->LitLights()[VehicleEnd::front] & light::headlight_left) != 0); + btLampkaRightLight.Turn((occupied->LitLights()[VehicleEnd::front] & light::headlight_right) != 0); + btLampkaLeftEndLight.Turn((occupied->LitLights()[VehicleEnd::front] & light::redmarker_left) != 0); + btLampkaRightEndLight.Turn((occupied->LitLights()[VehicleEnd::front] & light::redmarker_right) != 0); + btLampkaRearUpperLight.Turn((occupied->LitLights()[VehicleEnd::rear] & light::headlight_upper) != 0); + btLampkaRearLeftLight.Turn((occupied->LitLights()[VehicleEnd::rear] & light::headlight_left) != 0); + btLampkaRearRightLight.Turn((occupied->LitLights()[VehicleEnd::rear] & light::headlight_right) != 0); + btLampkaRearLeftEndLight.Turn((occupied->LitLights()[VehicleEnd::rear] & light::redmarker_left) != 0); + btLampkaRearRightEndLight.Turn((occupied->LitLights()[VehicleEnd::rear] & light::redmarker_right) != 0); // others btLampkaMalfunction.Turn(controlled->diesel.heat.PA); // overheat indicator lamps @@ -1389,7 +1389,7 @@ void TTrain::updateHeatingAndInstrumentLights() InstrumentLightType == 4 ? occupied->lowVoltage.Is24vAvailable() || occupied->lowVoltage.Is110vAvailable() : false)}; InstrumentLightActive = InstrumentLightType == 3 ? true : // TODO: link the light state with the state of the master key - InstrumentLightType == 4 ? occupied->iLights[VehicleEnd::front] != 0 || occupied->iLights[VehicleEnd::rear] != 0 : + InstrumentLightType == 4 ? occupied->LitLights()[VehicleEnd::front] != 0 || occupied->LitLights()[VehicleEnd::rear] != 0 : InstrumentLightActive; btInstrumentLight.Turn(InstrumentLightActive && lightpower); btDashboardLight.Turn(DashboardLightActive && lightpower); diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index 6e0c52cd6..3af162884 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -507,7 +507,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" { auto const indexstart { 0 }; auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; - physics->MaxLoad = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); + physics->SetMaxLoad(std::atoi( ActPar.substr( indexstart, indexend ).c_str() )); ActPar.erase( 0, indexend ); } while( false == ActPar.empty() ) { diff --git a/vehicle/dynamic/lights.cpp b/vehicle/dynamic/lights.cpp index 132ebcdb0..b531cd9c0 100644 --- a/vehicle/dynamic/lights.cpp +++ b/vehicle/dynamic/lights.cpp @@ -114,9 +114,9 @@ void TDynamicObject::RaLightsSet(int head, int rear) // w zależności od kierunku pojazdu w składzie if( head >= 0 ) { auto const vehicleend { iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear }; - physics->iLights[ vehicleend ] = head & iInventory[vehicleend]; - bool tLeft = physics->iLights[vehicleend] & (light::auxiliary_left | light::headlight_left); // roboczo czy jakiekolwiek swiatlo z lewej jest zapalone - bool tRight = physics->iLights[vehicleend] & (light::auxiliary_right | light::headlight_right); // a tu z prawej + physics->SetLitLights( vehicleend, head & iInventory[vehicleend] ); + bool tLeft = physics->LitLights()[vehicleend] & (light::auxiliary_left | light::headlight_left); // roboczo czy jakiekolwiek swiatlo z lewej jest zapalone + bool tRight = physics->LitLights()[vehicleend] & (light::auxiliary_right | light::headlight_right); // a tu z prawej if (Controller == Humandriver) { auto const dps{physics->currentDimPosition()}; @@ -128,7 +128,7 @@ void TDynamicObject::RaLightsSet(int head, int rear) // obsługa OFF if (dps.isOff) { - //physics->iLights[vehicleend] &= 0 | light::rearendsignals; // zostawiamy tylko tabliczki jesli sa + //physics->SetLitLights(vehicleend, physics->LitLights()[vehicleend] & (0 | light::rearendsignals)); // zostawiamy tylko tabliczki jesli sa HighBeamLights = false; DimHeadlights = false; // the headlights at the end of the active cab: A at the front, B at the rear @@ -156,7 +156,7 @@ void TDynamicObject::RaLightsSet(int head, int rear) } if( rear >= 0 ) { auto const vehicleend{ iDirection > 0 ? VehicleEnd::rear : VehicleEnd::front }; - physics->iLights[ vehicleend ] = rear & iInventory[vehicleend]; + physics->SetLitLights( vehicleend, rear & iInventory[vehicleend] ); } }; @@ -212,7 +212,7 @@ bool TDynamicObject::has_signal_pc1_on() const { auto const pattern { equippedlights & ( light::headlight_left | light::headlight_right | light::headlight_upper ) }; auto const patternfallback { equippedlights & ( light::auxiliary_left | light::auxiliary_right | light::headlight_upper ) }; auto const hasauxiliarylights { ( equippedlights & ( light::auxiliary_left | light::auxiliary_right ) ) != 0 }; - auto const activelights { physics->iLights[ vehicleend ] }; + auto const activelights { physics->LitLights()[ vehicleend ] }; return (pattern != 0 && activelights == pattern) || (hasauxiliarylights && activelights == patternfallback) || (pattern == 0 && patternfallback == 0 && activelights == light::rearendsignals); // pc4 @@ -225,7 +225,7 @@ bool TDynamicObject::has_signal_pc2_on() const { auto const pattern { equippedlights & ( light::redmarker_left | light::headlight_right | light::headlight_upper ) }; auto const patternfallback { equippedlights & ( light::redmarker_left | light::auxiliary_right | light::headlight_upper ) }; auto const hasauxiliarylights { ( equippedlights & ( light::auxiliary_left | light::auxiliary_right ) ) != 0 }; - auto const activelights { physics->iLights[ vehicleend ] }; + auto const activelights { physics->LitLights()[ vehicleend ] }; return activelights == pattern || (hasauxiliarylights && activelights == patternfallback); } @@ -236,7 +236,7 @@ bool TDynamicObject::has_signal_pc5_on() const { auto const equippedlights { iInventory[ vehicleend ] }; auto const pattern { equippedlights & ( light::redmarker_left | light::redmarker_right ) }; auto const patternfallback { equippedlights & light::rearendsignals }; - auto const activelights { physics->iLights[ vehicleend ] }; + auto const activelights { physics->LitLights()[ vehicleend ] }; return (pattern != 0 && activelights == pattern) || (patternfallback != 0 && activelights == patternfallback); } @@ -246,9 +246,9 @@ bool TDynamicObject::has_signal_on( VehicleEnd const Side, int const Pattern ) c auto const vehicleend { iDirection > 0 ? Side : 1 - Side }; auto const pattern { iInventory[ vehicleend ] & Pattern }; - return ( physics->iLights[ vehicleend ] == pattern ); + return ( physics->LitLights()[ vehicleend ] == pattern ); */ - return physics->iLights[Side] == (Pattern & iInventory[Side]); + return physics->LitLights()[Side] == (Pattern & iInventory[Side]); } TDimension const &TDynamicObject::Dimensions() const { @@ -295,7 +295,7 @@ bool TDynamicObject::LowVoltagePowered() const { } int TDynamicObject::LightsSwitchedOn( VehicleEnd const End ) const { - return physics->iLights[ End ]; + return physics->LitLights()[ End ]; } double TDynamicObject::HeadlightsMultiplier() const { diff --git a/vehicle/dynamic/load.cpp b/vehicle/dynamic/load.cpp index 026761d23..309fe4033 100644 --- a/vehicle/dynamic/load.cpp +++ b/vehicle/dynamic/load.cpp @@ -154,24 +154,20 @@ void TDynamicObject::update_exchange( double const Deltatime ) { m_exchange.time -= 1.0; auto const exchangesize = std::min( m_exchange.unload_count, physics->UnLoadSpeed * exchangespeed ); m_exchange.unload_count -= exchangesize; - physics->LoadStatus = 1; - physics->LoadAmount = std::max( 0.f, physics->LoadAmount - exchangesize ); - physics->ComputeMass(); + physics->UnloadStep( exchangesize ); update_load_visibility(); } if( m_exchange.unload_count < 0.01 ) { // finish any potential unloading operation before adding new load // don't load more than can fit - m_exchange.load_count = std::min( m_exchange.load_count, physics->MaxLoad - physics->LoadAmount ); + m_exchange.load_count = std::min( m_exchange.load_count, physics->MaxLoad() - physics->LoadAmount() ); while( m_exchange.load_count > 0.01 && m_exchange.time >= 1.0 ) { m_exchange.time -= 1.0; auto const exchangesize = std::min( m_exchange.load_count, physics->LoadSpeed * exchangespeed ); m_exchange.load_count -= exchangesize; - physics->LoadStatus = 2; - physics->LoadAmount = std::min( physics->MaxLoad, physics->LoadAmount + exchangesize ); // std::max not strictly needed but, eh - physics->ComputeMass(); + physics->LoadStep( exchangesize ); update_load_visibility(); } } @@ -187,7 +183,7 @@ void TDynamicObject::update_exchange( double const Deltatime ) { if( m_exchange.unload_count < 0.01 && m_exchange.load_count < 0.01 ) { - physics->LoadStatus = 4; + physics->FinishLoadExchange(); // if the exchange is completed (or canceled) close the door, if applicable if( physics->Doors.close_control == control_t::passenger || physics->Doors.close_control == control_t::mixed ) { @@ -202,7 +198,7 @@ void TDynamicObject::update_exchange( double const Deltatime ) { } } // if the vehicle was emptied potentially switch load visualization model - if( physics->LoadAmount == 0 ) { + if( physics->LoadAmount() == 0 ) { physics->AssignLoad( "" ); } } @@ -210,11 +206,10 @@ void TDynamicObject::update_exchange( double const Deltatime ) { void TDynamicObject::LoadUpdate() { - physics->LoadStatus &= 1 | 2; // po zakończeniu będzie równe zero + physics->AcknowledgeLoadExchange(); // po zakończeniu będzie równe zero // przeładowanie modelu ładunku - if( physics->LoadTypeChange ) { - // whether we succeed or not don't try more than once - physics->LoadTypeChange = false; + // whether we succeed or not don't try more than once + if( physics->TakeLoadTypeChange() ) { // bieżąca ścieżka do tekstur to dynamic/... Global.asCurrentTexturePath = asBaseDir; mdLoad = LoadMMediaFile_mdload( physics->LoadType.name ); @@ -264,9 +259,9 @@ TDynamicObject::update_load_visibility() { // each entry in load order sequence matches a single chunk of the section it points to // the length of load order sequence matches total number of load chunks auto const loadpercentage { ( - physics->MaxLoad == 0.f ? + physics->MaxLoad() == 0.f ? 0.0 : - physics->LoadAmount / physics->MaxLoad ) }; + physics->LoadAmount() / physics->MaxLoad() ) }; auto visiblechunkcount { ( SectionLoadOrder.empty() ? 0 : @@ -284,9 +279,9 @@ TDynamicObject::update_load_offset() { if( physics->LoadType.offset_min == 0.f ) { return; } auto const loadpercentage { ( - physics->MaxLoad == 0.f ? + physics->MaxLoad() == 0.f ? 0.0 : - 100.0 * physics->LoadAmount / physics->MaxLoad ) }; + 100.0 * physics->LoadAmount() / physics->MaxLoad() ) }; LoadOffset = std::lerp( physics->LoadType.offset_min, 0.f, safe_clamp( 0.0, 1.0, loadpercentage * 0.01 ) ); } diff --git a/vehicle/dynamic/movement.cpp b/vehicle/dynamic/movement.cpp index 3fd4687cc..0cccff345 100644 --- a/vehicle/dynamic/movement.cpp +++ b/vehicle/dynamic/movement.cpp @@ -293,7 +293,7 @@ bool TDynamicObject::FastUpdate(double dt) // ResetdMoveLen(); FastMove(dDOMoveLen); - if( physics->LoadStatus ) { + if( physics->LoadStatus() ) { LoadUpdate(); // zmiana modelu ładunku } update_exchange( dt ); diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index 8628b4b71..778b2163b 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -103,7 +103,7 @@ void TDynamicObject::RenderSounds() { renderPhysicsEventSounds(); renderCouplerSounds(); - physics->SoundFlag = 0; + physics->ClearSoundFlags(); // McZapkie! - koniec obslugi dzwiekow z physics.pas renderDerailmentSounds(); @@ -468,13 +468,13 @@ void TDynamicObject::renderSpringBrakeSounds() { void TDynamicObject::renderLoadExchangeSounds() { // load exchange - if( physics->LoadStatus & 1 ) { + if( physics->LoadStatus() & 1 ) { m_exchangesounds.unloading.play( sound_flags::exclusive ); } else { m_exchangesounds.unloading.stop(); } - if( physics->LoadStatus & 2 ) { + if( physics->LoadStatus() & 2 ) { m_exchangesounds.loading.play( sound_flags::exclusive ); } else { @@ -830,16 +830,16 @@ void TDynamicObject::renderStartJoltSound() { void TDynamicObject::renderPhysicsEventSounds() { // pneumatic relay - if( TestFlag( physics->SoundFlag, sound::pneumatic ) ) { + if( TestFlag( physics->SoundFlag(), sound::pneumatic ) ) { dsbPneumaticRelay .gain( - true == TestFlag( physics->SoundFlag, sound::loud ) ? + true == TestFlag( physics->SoundFlag(), sound::loud ) ? 1.0f : 0.8f ) .play(); } // door permit - if( TestFlag( physics->SoundFlag, sound::doorpermit ) ) { + if( TestFlag( physics->SoundFlag(), sound::doorpermit ) ) { // NOTE: current implementation doesn't discern between permit for left/right side, // which may be undesired in weird setups with doors only on one side // TBD, TODO: rework into dedicated sound event flag for each door location instance? @@ -983,13 +983,13 @@ void TDynamicObject::renderDerailmentSounds() { } // special events - if( physics->EventFlag ) { + if( physics->EventFlag() ) { // McZapkie: w razie wykolejenia if( true == physics->DamageFlag.HasAll(VehicleDamage::derailed) ) { rsDerailment.play( sound_flags::exclusive ); } - physics->EventFlag = false; + physics->ClearEventFlag(); } } @@ -1561,7 +1561,7 @@ void TDynamicObject::powertrain_sounds::renderRelaySounds( physics::Vehicle const &Vehicle ) { // relay sounds - auto const soundflags { Vehicle.SoundFlag }; + auto const soundflags { Vehicle.SoundFlag() }; if( TestFlag( soundflags, sound::relay ) ) { // przekaznik - gdy bezpiecznik, automatyczny rozruch itp if( true == TestFlag( soundflags, sound::shuntfield ) ) { diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index e14973129..f21a5241b 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -176,7 +176,7 @@ bool TDynamicObject::Update(double dt, double dt1) physics->InactiveCabPantsCheck = false; } - if( physics->LoadStatus ) { + if( physics->LoadStatus() ) { LoadUpdate(); // zmiana modelu ładunku } update_exchange( dt ); @@ -356,7 +356,7 @@ void TDynamicObject::switchOffMainsWithoutBattery() if( physics->MainSwitch( false, physics->TrainType == train_type::emu ? range_t::unit : range_t::local ) ) { // wyłączyć zasilanie // NOTE: we turn off entire EMU, but only the affected unit for other multi-unit consists - physics->EventFlag = true; + physics->RaiseEventFlag(); // drop pantographs // NOTE: this isn't universal behaviour // TODO: have this dependant on .fiz-driven flag diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index 544866862..f9698ae9a 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -650,7 +650,7 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio std::begin( m_groups[ group ] ), std::end( m_groups[ group ] ), [ this ]( std::uint32_t const Index ) { auto const *vehicle { m_items[ Index ] }; - return ( vehicle->physics->LoadStatus != 0 ) || ( vehicle->LoadExchangeTime() > 0.f ); } ) }; + return ( vehicle->physics->LoadStatus() != 0 ) || ( vehicle->LoadExchangeTime() > 0.f ); } ) }; ( loading ? m_maingroups : m_threadgroups ).push_back( static_cast( group ) ); } std::sort( diff --git a/vehicle/dynamic/visual.cpp b/vehicle/dynamic/visual.cpp index df1326fc9..0bb307857 100644 --- a/vehicle/dynamic/visual.cpp +++ b/vehicle/dynamic/visual.cpp @@ -349,36 +349,36 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) if (physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable()) { // sygnaly konca pociagu if (m_endsignals1.Active()) { - if (TestFlag(physics->iLights[VehicleEnd::front], light::redmarker_left | light::redmarker_right ) ) { + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::redmarker_left | light::redmarker_right ) ) { m_endsignals1.Turn( true ); btnOn = true; } } else { - if (TestFlag(physics->iLights[VehicleEnd::front], light::redmarker_left) && !HeadlightsAoff) + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::redmarker_left) && !HeadlightsAoff) { m_endsignal13.Turn( true ); btnOn = true; } - if (TestFlag(physics->iLights[VehicleEnd::front], light::redmarker_right) && !HeadlightsAoff) + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::redmarker_right) && !HeadlightsAoff) { m_endsignal12.Turn( true ); btnOn = true; } } if (m_endsignals2.Active()) { - if (TestFlag(physics->iLights[VehicleEnd::rear], light::redmarker_left | light::redmarker_right ) ) { + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::redmarker_left | light::redmarker_right ) ) { m_endsignals2.Turn( true ); btnOn = true; } } else { - if (TestFlag(physics->iLights[VehicleEnd::rear], light::redmarker_left) && !HeadlightsBoff) + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::redmarker_left) && !HeadlightsBoff) { m_endsignal23.Turn( true ); btnOn = true; } - if (TestFlag(physics->iLights[VehicleEnd::rear], light::redmarker_right) && !HeadlightsBoff) + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::redmarker_right) && !HeadlightsBoff) { m_endsignal22.Turn( true ); btnOn = true; @@ -386,12 +386,12 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } } // tablice blaszane: - if (TestFlag(physics->iLights[VehicleEnd::front], light::rearendsignals)) { + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::rearendsignals)) { m_endtab1.Turn( true ); btnOn = true; } // else btEndSignalsTab1.TurnOff(); - if (TestFlag(physics->iLights[VehicleEnd::rear], light::rearendsignals)) { + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::rearendsignals)) { m_endtab2.Turn( true ); btnOn = true; } @@ -446,7 +446,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) // ograniczeń odległości, by były widoczne z // daleka - if (TestFlag(physics->iLights[VehicleEnd::front], light::headlight_left) + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::headlight_left) && !HeadlightsAoff && !HighBeamLights) { if( DimHeadlights ) { @@ -457,7 +457,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(physics->iLights[VehicleEnd::front], light::headlight_upper) + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::headlight_upper) && !HeadlightsAoff) { if( DimHeadlights ) { @@ -468,7 +468,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(physics->iLights[VehicleEnd::front], light::headlight_right) + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::headlight_right) && !HeadlightsAoff && !HighBeamLights) { if( DimHeadlights ) { @@ -480,7 +480,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } // else btHeadSignals13.TurnOff(); - if (TestFlag(physics->iLights[VehicleEnd::rear], light::headlight_left) + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::headlight_left) && !HeadlightsBoff && !HighBeamLights) { if( DimHeadlights ) { @@ -491,7 +491,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(physics->iLights[VehicleEnd::rear], light::headlight_upper) + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::headlight_upper) && !HeadlightsBoff) { if( DimHeadlights ) { @@ -502,7 +502,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(physics->iLights[VehicleEnd::rear], light::headlight_right) + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::headlight_right) && !HeadlightsBoff && !HighBeamLights) { if( DimHeadlights ) { @@ -514,7 +514,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) btnOn = true; } // auxiliary lights - if (TestFlag(physics->iLights[VehicleEnd::front], light::auxiliary_left) && !HeadlightsAoff) + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::auxiliary_left) && !HeadlightsAoff) { if( DimHeadlights ) { m_headsignal13.TurnxOnWithOnAsFallback(); @@ -524,7 +524,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(physics->iLights[VehicleEnd::front], light::auxiliary_right) && !HeadlightsAoff) + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::auxiliary_right) && !HeadlightsAoff) { if( DimHeadlights ) { m_headsignal12.TurnxOnWithOnAsFallback(); @@ -534,7 +534,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(physics->iLights[VehicleEnd::rear], light::auxiliary_left) && !HeadlightsBoff) + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::auxiliary_left) && !HeadlightsBoff) { if( DimHeadlights ) { m_headsignal23.TurnxOnWithOnAsFallback(); @@ -544,7 +544,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } btnOn = true; } - if (TestFlag(physics->iLights[VehicleEnd::rear], light::auxiliary_right) && !HeadlightsBoff) + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::auxiliary_right) && !HeadlightsBoff) { if( DimHeadlights ) { m_headsignal22.TurnxOnWithOnAsFallback(); @@ -556,26 +556,26 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) } // logika dlugich - if (TestFlag(physics->iLights[VehicleEnd::front], light::headlight_left) + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::headlight_left) && !HeadlightsAoff && HighBeamLights) m_highbeam13.TurnxOnWithOnAsFallback(); else m_highbeam13.TurnOff(); - if (TestFlag(physics->iLights[VehicleEnd::front], light::headlight_right) + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::headlight_right) && !HeadlightsAoff && HighBeamLights) m_highbeam12.TurnxOnWithOnAsFallback(); else m_highbeam12.TurnOff(); // i to samo od dupy strony - if (TestFlag(physics->iLights[VehicleEnd::rear], light::headlight_left) + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::headlight_left) && !HeadlightsBoff && HighBeamLights) m_highbeam23.TurnxOnWithOnAsFallback(); else m_highbeam23.TurnOff(); - if (TestFlag(physics->iLights[VehicleEnd::rear], light::headlight_right) + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::headlight_right) && !HeadlightsBoff && HighBeamLights) m_highbeam22.TurnxOnWithOnAsFallback(); else diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index 14d708950..b80cb28a7 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -80,17 +80,17 @@ void ui::vehicleparams_panel::draw_mini(const physics::Vehicle &physics) if (physics.WarningSignal()) draw_infobutton(STR_C("horn"), ImVec2(361, 11)); - if (physics.iLights[VehicleEnd::front] & light::redmarker_left) + if (physics.LitLights()[VehicleEnd::front] & light::redmarker_left) draw_infobutton("o", ImVec2(490, 71), ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); - else if (physics.iLights[VehicleEnd::front] & light::headlight_left) + else if (physics.LitLights()[VehicleEnd::front] & light::headlight_left) draw_infobutton("O", ImVec2(490, 71), ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - if (physics.iLights[VehicleEnd::front] & light::redmarker_right) + if (physics.LitLights()[VehicleEnd::front] & light::redmarker_right) draw_infobutton("o", ImVec2(443, 71), ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); - else if (physics.iLights[VehicleEnd::front] & light::headlight_right) + else if (physics.LitLights()[VehicleEnd::front] & light::headlight_right) draw_infobutton("O", ImVec2(443, 71), ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - if (physics.iLights[VehicleEnd::front] & light::headlight_upper) + if (physics.LitLights()[VehicleEnd::front] & light::headlight_upper) draw_infobutton("O", ImVec2(467, 18), ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); } ImGui::EndChild(); diff --git a/world/Event.cpp b/world/Event.cpp index 4c8283742..b1c17dc6b 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -1065,15 +1065,15 @@ whois_event::run_() { // jeśli parametry ładunku targetcell->UpdateValues( m_activator->physics->LoadType.name, // nazwa ładunku - m_activator->physics->LoadAmount, // aktualna ilość - m_activator->physics->MaxLoad, // maksymalna ilość + m_activator->physics->LoadAmount(), // aktualna ilość + m_activator->physics->MaxLoad(), // maksymalna ilość m_input.flags & ( flags::text | flags::value1 | flags::value2 ) ); WriteLog( "Type: WhoIs (" + std::to_string( m_input.flags ) + ") - " + "[load type: " + m_activator->physics->LoadType.name + "], " - + "[current load: " + to_string( m_activator->physics->LoadAmount, 2 ) + "], " - + "[max load: " + to_string( m_activator->physics->MaxLoad, 2 ) + "]" ); + + "[current load: " + to_string( m_activator->physics->LoadAmount(), 2 ) + "], " + + "[max load: " + to_string( m_activator->physics->MaxLoad(), 2 ) + "]" ); } } // +8 diff --git a/world/station.cpp b/world/station.cpp index 40c343118..c5572133e 100644 --- a/world/station.cpp +++ b/world/station.cpp @@ -49,7 +49,7 @@ basic_station::update_load( TDynamicObject *First, Mtable::TTrainParameters &Sch if( parameters.LoadType.name.empty() ) { // (try to) set the cargo type for empty cars - parameters.LoadAmount = 0.f; // safety measure against edge cases + parameters.SetLoadAmount(0.f); // safety measure against edge cases parameters.AssignLoad( "passengers" ); parameters.ComputeMass(); } @@ -58,18 +58,18 @@ basic_station::update_load( TDynamicObject *First, Mtable::TTrainParameters &Sch // NOTE: for the time being we're doing simple, random load change calculation // TODO: exchange driven by station parameters and time of the day auto unloadcount = static_cast( - parameters.DamageFlag.HasAll(VehicleDamage::derailed) ? parameters.LoadAmount : - laststop ? parameters.LoadAmount : + parameters.DamageFlag.HasAll(VehicleDamage::derailed) ? parameters.LoadAmount() : + laststop ? parameters.LoadAmount() : firststop ? 0 : maintenancestop ? 0 : std::min( - parameters.LoadAmount, - static_cast(Random( parameters.MaxLoad * 0.15f * stationsizemodifier )) ) ); + parameters.LoadAmount(), + static_cast(Random( parameters.MaxLoad() * 0.15f * stationsizemodifier )) ) ); auto loadcount = static_cast( parameters.DamageFlag.HasAll(VehicleDamage::derailed) ? 0 : laststop ? 0 : maintenancestop ? 0 : - Random( parameters.MaxLoad * 0.15f * stationsizemodifier ) ); + Random( parameters.MaxLoad() * 0.15f * stationsizemodifier ) ); if( true == firststop ) { // larger group at the initial station loadcount *= 2; From 0b5459ef7bd385b94e6cf606cec406426e30e59c Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 12:38:26 +0100 Subject: [PATCH 22/30] refactor(physics): the positions of the brake handles are private to the brakes The positions of the driver's brake valve (stepped, continuous, and of the FV4a with its cap), of the independent brake and of its EP counterpart in units with induction motors, and of the hand brake are private to physics::Braking: read through HandlePosition(), IndependentPosition(), ... and moved through SetHandlePosition(), SetIndependentPosition(), ..., by the vehicle's own stepping as by the cab, the AI and the consist braking. The gauges of the cab bind to them read-only. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- application/driverhints.cpp | 16 +++--- application/driveruipanels.cpp | 10 ++-- input/drivermouseinput.cpp | 6 +- physics/components/body.cpp | 4 +- physics/components/braking.h | 31 ++++++++--- physics/components/commands.cpp | 2 +- physics/components/controllers.cpp | 10 ++-- physics/components/pneumatics.cpp | 86 ++++++++++++++--------------- physics/components/setup.cpp | 14 ++--- physics/components/traction.cpp | 2 +- physics/consistbraking.cpp | 16 +++--- simulation/blackboxrecorder.cpp | 6 +- tests/unit/golden.cpp | 6 +- tests/unit/invariants.cpp | 4 +- tests/unit/test_brake_handles.cpp | 2 +- tests/unit/test_brakes.cpp | 2 +- tests/unit/test_cab.cpp | 2 +- tests/unit/test_consist_braking.cpp | 6 +- tests/unit/test_crew.cpp | 8 +-- tests/unit/test_drivingaid.cpp | 12 ++-- tests/unit/test_elf_controller.cpp | 2 +- tests/unit/test_pullee.cpp | 8 +-- tests/unit/vehicle.cpp | 8 +-- vehicle/ai/consist.cpp | 12 ++-- vehicle/ai/controls.cpp | 26 ++++----- vehicle/ai/engine.cpp | 4 +- vehicle/ai/force.cpp | 12 ++-- vehicle/ai/physicslog.cpp | 4 +- vehicle/ai/situation.cpp | 2 +- vehicle/ai/speed.cpp | 2 +- vehicle/cab/brakecommands.cpp | 20 +++---- vehicle/cab/controllercommands.cpp | 8 +-- vehicle/cab/setup.cpp | 4 +- vehicle/cab/train.cpp | 14 ++--- vehicle/cab/update.cpp | 10 ++-- vehicle/drivingaid.cpp | 4 +- vehicle/dynamic/lifecycle.cpp | 12 ++-- vehicle/dynamic/sounds.cpp | 4 +- widgets/vehicleparams.cpp | 4 +- 39 files changed, 210 insertions(+), 195 deletions(-) diff --git a/application/driverhints.cpp b/application/driverhints.cpp index fcc9b48dc..7750339f3 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -490,7 +490,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this]( float const /*Parameter*/ ) { - return occupied->brakes.config.localKind != TLocalBrake::ManualBrake || occupied->brakes.config.hasHandBrake == false || occupied->brakes.handBrakePosition == ManualBrakePosNo; } ); + return occupied->brakes.config.localKind != TLocalBrake::ManualBrake || occupied->brakes.config.hasHandBrake == false || occupied->brakes.HandBrakePosition() == ManualBrakePosNo; } ); break; } case driver_hint::manualbrakoff: { @@ -501,7 +501,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this]( float const /*Parameter*/ ) { - return occupied->brakes.config.localKind != TLocalBrake::ManualBrake || occupied->brakes.config.hasHandBrake == false || occupied->brakes.handBrakePosition == 0; } ); + return occupied->brakes.config.localKind != TLocalBrake::ManualBrake || occupied->brakes.config.hasHandBrake == false || occupied->brakes.HandBrakePosition() == 0; } ); break; } // master controller @@ -818,7 +818,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return is_equal(occupied->brakes.handlePositionSmooth, occupied->brakes.driverValve->GetPos(bh_RP), 0.2) || (occupied->brakes.driverValve->Time && occupied->brakes.driverValve->GetCP() > occupied->brakes.config.pipeHighPressure - 0.05); } ); + return is_equal(occupied->brakes.HandlePositionSmooth(), occupied->brakes.driverValve->GetPos(bh_RP), 0.2) || (occupied->brakes.driverValve->Time && occupied->brakes.driverValve->GetCP() > occupied->brakes.config.pipeHighPressure - 0.05); } ); // return ( BrakeCtrlPosition == gbh_RP ); } ); break; } @@ -867,7 +867,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) { - return std::abs(mvControlling->Fb) > Parameter || is_equal(occupied->brakes.handlePositionSmooth, occupied->brakes.driverValve->GetPos(bh_EB), 0.2); }, + return std::abs(mvControlling->Fb) > Parameter || is_equal(occupied->brakes.HandlePositionSmooth(), occupied->brakes.driverValve->GetPos(bh_EB), 0.2); }, static_cast(std::max( 0.0, std::max( @@ -885,7 +885,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return Ready && fReady < 0.4 && is_equal(occupied->brakes.handlePositionSmooth, occupied->brakes.driverValve->GetPos(bh_RP), 0.2); } ); + return Ready && fReady < 0.4 && is_equal(occupied->brakes.HandlePositionSmooth(), occupied->brakes.driverValve->GetPos(bh_RP), 0.2); } ); break; } case driver_hint::brakingforcelap: { @@ -899,7 +899,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // independent brake case driver_hint::independentbrakeapply: { - if (AIControllFlag && occupied->brakes.independentPosition < 1.0) { + if (AIControllFlag && occupied->brakes.IndependentPosition() < 1.0) { occupied->IncLocalBrakeLevel( LocalBrakePosNo ); if (occupied->EIMCtrlEmergency) { occupied->DecLocalBrakeLevel(1); @@ -909,7 +909,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) { - return occupied->brakes.independentPosition >= Parameter; }, + return occupied->brakes.IndependentPosition() >= Parameter; }, ( LocalBrakePosNo - ( occupied->EIMCtrlEmergency ? 1 : 0 ) ) / LocalBrakePosNo ); break; } @@ -921,7 +921,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->brakes.independentPosition < 0.05; } ); + return occupied->brakes.IndependentPosition() < 0.05; } ); break; } // reverser diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index ae9eebe15..e474514f4 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -923,13 +923,13 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Brakes:\n train: %.2f (mode: %d, delay: %s, load flag: %d)\n independent: %.2f (%.2f), manual: %.2f, spring: %.2f\nBrake cylinder pressures:\n train: %.2f, independent: %.2f, status: 0x%.2x\nPipe pressures:\n brake: %.2f (hat: %.2f), main: %.2f, control: %.2f\nTank pressures:\n auxiliary: %.2f, main: %.2f, control: %.2f"), // brakes - physics.brakes.handlePositionSmooth, + physics.brakes.HandlePositionSmooth(), physics.brakes.operatingMode, update_vehicle_brake().c_str(), physics.brakes.loadSetting, - physics.brakes.independentPosition, - physics.brakes.independentPositionEim, - static_cast(physics.brakes.handBrakePosition) / static_cast(ManualBrakePosNo), + physics.brakes.IndependentPosition(), + physics.brakes.IndependentPositionEim(), + static_cast(physics.brakes.HandBrakePosition()) / static_cast(ManualBrakePosNo), physics.brakes.spring.activate ? 1.f : 0.f, // cylinders physics.brakes.cylinderPressure, @@ -937,7 +937,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.brakes.distributor->GetBrakeStatus(), // pipes physics.brakePipe.Pressure(), - physics.brakes.handleCapPosition, + physics.brakes.HandleCapPosition(), physics.mainPipe.Pressure(), physics.brakes.controlReservoirPressure, // tanks diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index 299dac67b..37bc1992c 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -73,7 +73,7 @@ mouse_slider::bind( user_command const &Command ) { + 0.5 * ( vehicle->CoupledCtrl ? vehicle->MainCtrlPos() + vehicle->ScndCtrlPos() : vehicle->MainCtrlPos() ) / powerrange - - 0.5 * occupied->brakes.independentPosition; + - 0.5 * occupied->brakes.IndependentPosition(); m_analogue = true; m_invertrange = false; break; @@ -94,14 +94,14 @@ mouse_slider::bind( user_command const &Command ) { } case user_command::trainbrakeset: { m_valuerange = 1.0; - m_value = ( vehicle->brakes.handlePositionSmooth - vehicle->brakes.driverValve->GetPos( bh_MIN ) ) / ( vehicle->brakes.driverValve->GetPos( bh_MAX ) - vehicle->brakes.driverValve->GetPos( bh_MIN ) ); + m_value = ( vehicle->brakes.HandlePositionSmooth() - vehicle->brakes.driverValve->GetPos( bh_MIN ) ) / ( vehicle->brakes.driverValve->GetPos( bh_MAX ) - vehicle->brakes.driverValve->GetPos( bh_MIN ) ); m_analogue = true; m_invertrange = true; break; } case user_command::independentbrakeset: { m_valuerange = 1.0; - m_value = vehicle->brakes.independentPosition; + m_value = vehicle->brakes.IndependentPosition(); m_analogue = true; m_invertrange = true; break; diff --git a/physics/components/body.cpp b/physics/components/body.cpp index 145f7e141..6264ff513 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -1266,7 +1266,7 @@ bool physics::Vehicle::brakes_changed_asleep() const return false; constexpr double pressure_change{0.05}; // [bar] return std::abs(brakes.cylinderPressure - sleep_brakes.cylinder) > pressure_change || std::abs(brakes.spring.pressure - sleep_brakes.spring) > pressure_change || - brakes.handBrakePosition != sleep_brakes.manual || std::abs(brakes.independentPosition - sleep_brakes.local) > 0.01; + brakes.HandBrakePosition() != sleep_brakes.manual || std::abs(brakes.IndependentPosition() - sleep_brakes.local) > 0.01; } // ************************************************************************************************* @@ -1288,7 +1288,7 @@ bool physics::Vehicle::switch_physics(bool const State, wake_cause const Cause) else { // what the brake force of the last step came from, which it keeps while asleep (brakes_changed_asleep()) - sleep_brakes = {brakes.cylinderPressure, brakes.spring.pressure, brakes.handBrakePosition, brakes.independentPosition}; + sleep_brakes = {brakes.cylinderPressure, brakes.spring.pressure, brakes.HandBrakePosition(), brakes.IndependentPosition()}; } return true; diff --git a/physics/components/braking.h b/physics/components/braking.h index 9aeb5f5ab..a767be94f 100644 --- a/physics/components/braking.h +++ b/physics/components/braking.h @@ -223,13 +223,20 @@ struct Braking double pipeFlow = 0.0; // of the brake pipe, double driverValveFlow = 0.0; // through the driver's valve, double independentValveFlow = 0.0; // through the valve of the independent brake - int handlePosition = -2; // the position of the driver's valve - double handlePositionReal = 0.0; // the same, continuous, of the FV4a - double handleCapPosition = 0.0; // the cap of the FV4a - double handlePositionSmooth = -2.0; // the continuous position of the driver's valve - double independentPosition = 0.0; // the position of the independent brake - double independentPositionEim = 0.0; // the position of the EP independent brake of the asynchronous EMUs - int handBrakePosition = 0; + int const &HandlePosition() const { return handlePosition; } // the position of the driver's valve + void SetHandlePosition(int const Value) { handlePosition = Value; } + double const &HandlePositionReal() const { return handlePositionReal; } // the same, continuous, of the FV4a + void SetHandlePositionReal(double const Value) { handlePositionReal = Value; } + double const &HandleCapPosition() const { return handleCapPosition; } // the cap of the FV4a + void SetHandleCapPosition(double const Value) { handleCapPosition = Value; } + double const &HandlePositionSmooth() const { return handlePositionSmooth; } // the continuous position of the driver's valve + void SetHandlePositionSmooth(double const Value) { handlePositionSmooth = Value; } + double const &IndependentPosition() const { return independentPosition; } // the position of the independent brake + void SetIndependentPosition(double const Value) { independentPosition = Value; } + double const &IndependentPositionEim() const { return independentPositionEim; } // the position of the EP independent brake of the asynchronous EMUs + void SetIndependentPositionEim(double const Value) { independentPositionEim = Value; } + int const &HandBrakePosition() const { return handBrakePosition; } + void SetHandBrakePosition(int const Value) { handBrakePosition = Value; } int status = 0; // the bits b_* (b_off 0, b_on, b_dmg, b_rls, b_asb, b_ep ...) bool alarmChain = false; // the manual emergency brake int delaySetting = 0; // the delay set (bdelay_*) @@ -245,6 +252,16 @@ struct Braking EmuDynamicBrake emuDynamic; HoldingBrake holding; SpringBrake spring; + + private: + // the positions of the handles: the driver, the cab and the AI move them through the operations above + int handlePosition = -2; + double handlePositionReal = 0.0; + double handleCapPosition = 0.0; + double handlePositionSmooth = -2.0; + double independentPosition = 0.0; + double independentPositionEim = 0.0; + int handBrakePosition = 0; }; } // namespace physics diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 65d16f643..f8e9130a3 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -285,7 +285,7 @@ bool physics::Vehicle::RunBrakeCommand(VehicleCommand const Command, double CVal if (CValue1 < 0.001) brakes.electrodynamic.emuWorking = true; // fBrakeCtrlPos:=BrakeCtrlPos; //to powinnno być w jednym miejscu, aktualnie w C++!!! - brakes.actualPressure = brakes.config.pressureTable[brakes.handlePosition]; + brakes.actualPressure = brakes.config.pressureTable[brakes.HandlePosition()]; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } // youby - odluzniacz hamulcow, przyda sie else if (Command == VehicleCommand::brakeReleaser) diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index f16a99577..17e34428e 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -1168,17 +1168,17 @@ void physics::Vehicle::EIMICFromUniversalController(double dt, double const brak // controller, at a brake handle moved alone, to the nearest position of the handle's void physics::Vehicle::UniversalControllerTrainBrake() { - if (UniCtrlList[mainCtrlPos].mode != brakes.handlePosition && MainCtrlActualPos == mainCtrlPos) // there was no move of controller, but brake only + if (UniCtrlList[mainCtrlPos].mode != brakes.HandlePosition() && MainCtrlActualPos == mainCtrlPos) // there was no move of controller, but brake only { - if (brakes.handlePosition < UniCtrlList[MainCtrlPosNo].mode) + if (brakes.HandlePosition() < UniCtrlList[MainCtrlPosNo].mode) BrakeLevelSet(UniCtrlList[MainCtrlPosNo].mode); // bottom clamping - if (brakes.handlePosition > UniCtrlList[0].mode) + if (brakes.HandlePosition() > UniCtrlList[0].mode) BrakeLevelSet(UniCtrlList[0].mode); // top clamping if (IsCabMaster()) { - while (brakes.handlePosition > UniCtrlList[mainCtrlPos].mode) + while (brakes.HandlePosition() > UniCtrlList[mainCtrlPos].mode) DecMainCtrl(1); // find nearest position - while (brakes.handlePosition < UniCtrlList[mainCtrlPos].mode) + while (brakes.HandlePosition() < UniCtrlList[mainCtrlPos].mode) IncMainCtrl(1); // find nearest position } } diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 5ac5ccf5d..f057e4cce 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -35,24 +35,24 @@ http://mozilla.org/MPL/2.0/. void physics::Vehicle::BrakeLevelSet(double b) { // ustawienie pozycji hamulca na wartość (b) w zakresie od -2 do BrakeCtrlPosNo // jedyny dopuszczalny sposób przestawienia hamulca zasadniczego - if (brakes.handlePositionSmooth == b) + if (brakes.HandlePositionSmooth() == b) return; // nie przeliczać, jak nie ma zmiany - brakes.handlePositionSmooth = b; - if (brakes.handlePositionSmooth < brakes.driverValve->GetPos(bh_MIN)) - brakes.handlePositionSmooth = brakes.driverValve->GetPos(bh_MIN); // odcięcie - else if (brakes.handlePositionSmooth > brakes.driverValve->GetPos(bh_MAX)) - brakes.handlePositionSmooth = brakes.driverValve->GetPos(bh_MAX); + brakes.SetHandlePositionSmooth(b); + if (brakes.HandlePositionSmooth() < brakes.driverValve->GetPos(bh_MIN)) + brakes.SetHandlePositionSmooth(brakes.driverValve->GetPos(bh_MIN)); // odcięcie + else if (brakes.HandlePositionSmooth() > brakes.driverValve->GetPos(bh_MAX)) + brakes.SetHandlePositionSmooth(brakes.driverValve->GetPos(bh_MAX)); // TODO: verify whether BrakeCtrlPosR and fBrakeCtrlPos can be rolled into single variable - brakes.handlePositionReal = brakes.handlePositionSmooth; - auto x = static_cast(std::floor(brakes.handlePositionSmooth)); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być + brakes.SetHandlePositionReal(brakes.HandlePositionSmooth()); + auto x = static_cast(std::floor(brakes.HandlePositionSmooth())); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być // obcięte a nie zaokrągone - while (x > brakes.handlePosition && brakes.handlePosition < brakes.config.handlePositions) // jeśli zwiększyło się o 1 + while (x > brakes.HandlePosition() && brakes.HandlePosition() < brakes.config.handlePositions) // jeśli zwiększyło się o 1 if (!IncBrakeLevelOld()) // physics::Vehicle:: break; // wyjście awaryjne - while (x < brakes.handlePosition && brakes.handlePosition >= -1) // jeśli zmniejszyło się o 1 + while (x < brakes.HandlePosition() && brakes.HandlePosition() >= -1) // jeśli zmniejszyło się o 1 if (!DecBrakeLevelOld()) // physics::Vehicle:: break; - brakes.actualPressure = brakes.config.pressureTable[brakes.handlePosition]; // skopiowanie pozycji + brakes.actualPressure = brakes.config.pressureTable[brakes.HandlePosition()]; // skopiowanie pozycji /* //youBy: obawiam sie, ze tutaj to nie dziala :P //Ra 2014-03: było tak zrobione, że działało - po każdej zmianie pozycji była wywoływana ta @@ -76,8 +76,8 @@ void physics::Vehicle::BrakeLevelSet(double b) bool physics::Vehicle::BrakeLevelAdd(double b) { // dodanie wartości (b) do pozycji hamulca (w tym ujemnej) // zwraca false, gdy po dodaniu było by poza zakresem - BrakeLevelSet(brakes.handlePositionSmooth + b); - return b > 0.0 ? brakes.handlePositionSmooth < brakes.config.handlePositions : brakes.handlePosition > -1.0; // true, jeśli można kontynuować + BrakeLevelSet(brakes.HandlePositionSmooth() + b); + return b > 0.0 ? brakes.HandlePositionSmooth() < brakes.config.handlePositions : brakes.HandlePosition() > -1.0; // true, jeśli można kontynuować }; bool physics::Vehicle::IncBrakeLevel() @@ -138,13 +138,13 @@ double physics::Vehicle::LocalBrakeRatio(void) const double LBR; if (brakes.config.driverValveType == TBrakeHandle::MHZ_EN57) if (brakes.operatingMode >= bom_EP) - LBR = brakes.driverValve->GetEP(brakes.handlePositionReal); + LBR = brakes.driverValve->GetEP(brakes.HandlePositionReal()); else LBR = 0; else { if (LocalBrakePosNo > 0) - LBR = brakes.independentPosition; + LBR = brakes.IndependentPosition(); else LBR = 0; } @@ -162,7 +162,7 @@ double physics::Vehicle::ManualBrakeRatio(void) const double MBR; if (ManualBrakePosNo > 0) - MBR = (double)brakes.handBrakePosition / ManualBrakePosNo; + MBR = (double)brakes.HandBrakePosition() / ManualBrakePosNo; else MBR = 0; return MBR; @@ -354,12 +354,12 @@ bool physics::Vehicle::IncBrakeLevelOld(void) if (brakes.config.handlePositions > 0) { - if (brakes.handlePosition < brakes.config.handlePositions) + if (brakes.HandlePosition() < brakes.config.handlePositions) { - ++brakes.handlePosition; + brakes.SetHandlePosition(brakes.HandlePosition() + 1); // youBy: EP po nowemu IBLO = true; - if (brakes.actualPressure.PipePressureVal < 0 && brakes.config.pressureTable[brakes.handlePosition - 1].PipePressureVal > 0) + if (brakes.actualPressure.PipePressureVal < 0 && brakes.config.pressureTable[brakes.HandlePosition() - 1].PipePressureVal > 0) brakes.pipeLimiterPressure = brakePipe.Pressure(); } else @@ -381,9 +381,9 @@ bool physics::Vehicle::DecBrakeLevelOld(void) if (brakes.config.handlePositions > 0) { - if (brakes.handlePosition > (brakes.config.driverValveType == TBrakeHandle::FV4a ? -2 : -1)) + if (brakes.HandlePosition() > (brakes.config.driverValveType == TBrakeHandle::FV4a ? -2 : -1)) { - --brakes.handlePosition; + brakes.SetHandlePosition(brakes.HandlePosition() - 1); // youBy: EP po nowemu DBLO = true; // if ((BrakePressureTable[BrakeCtrlPos].PipePressureVal<0.0) && @@ -404,9 +404,9 @@ bool physics::Vehicle::DecBrakeLevelOld(void) bool physics::Vehicle::IncLocalBrakeLevel(float const CtrlSpeed) { bool IBL; - if (brakes.independentPosition < 1.0 /*and (BrakeCtrlPos<1)*/) + if (brakes.IndependentPosition() < 1.0 /*and (BrakeCtrlPos<1)*/) { - brakes.independentPosition = std::min(1.0, brakes.independentPosition + CtrlSpeed / LocalBrakePosNo); + brakes.SetIndependentPosition(std::min(1.0, brakes.IndependentPosition() + CtrlSpeed / LocalBrakePosNo)); wake_for_brake(); IBL = true; } @@ -423,9 +423,9 @@ bool physics::Vehicle::IncLocalBrakeLevel(float const CtrlSpeed) bool physics::Vehicle::DecLocalBrakeLevel(float const CtrlSpeed) { bool DBL; - if (brakes.independentPosition > 0) + if (brakes.IndependentPosition() > 0) { - brakes.independentPosition = std::max(0.0, brakes.independentPosition - CtrlSpeed / LocalBrakePosNo); + brakes.SetIndependentPosition(std::max(0.0, brakes.IndependentPosition() - CtrlSpeed / LocalBrakePosNo)); wake_for_brake(); DBL = true; } @@ -442,11 +442,11 @@ bool physics::Vehicle::DecLocalBrakeLevel(float const CtrlSpeed) bool physics::Vehicle::IncManualBrakeLevel(int CtrlSpeed) { bool IMBL; - if (brakes.handBrakePosition < ManualBrakePosNo) /*and (BrakeCtrlPos<1)*/ + if (brakes.HandBrakePosition() < ManualBrakePosNo) /*and (BrakeCtrlPos<1)*/ { - while (brakes.handBrakePosition < ManualBrakePosNo && CtrlSpeed > 0) + while (brakes.HandBrakePosition() < ManualBrakePosNo && CtrlSpeed > 0) { - brakes.handBrakePosition++; + brakes.SetHandBrakePosition(brakes.HandBrakePosition() + 1); CtrlSpeed--; } wake_for_brake(); @@ -465,11 +465,11 @@ bool physics::Vehicle::IncManualBrakeLevel(int CtrlSpeed) bool physics::Vehicle::DecManualBrakeLevel(int CtrlSpeed) { bool DMBL; - if (brakes.handBrakePosition > 0) + if (brakes.HandBrakePosition() > 0) { - while (CtrlSpeed > 0 && brakes.handBrakePosition > 0) + while (CtrlSpeed > 0 && brakes.HandBrakePosition() > 0) { - brakes.handBrakePosition--; + brakes.SetHandBrakePosition(brakes.HandBrakePosition() - 1); CtrlSpeed--; } wake_for_brake(); @@ -887,7 +887,7 @@ void physics::Vehicle::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 = brakes.config.independentTraxx ? eim_localbrake : brakes.independentPosition; + double lbpa = brakes.config.independentTraxx ? eim_localbrake : brakes.IndependentPosition(); if (EIMCtrlType > 0 && UniCtrlIntegratedLocalBrakeCtrl) { lbpa = std::max(0.0, -eimic_real); @@ -896,7 +896,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) { lbpa = std::max(lbpa, brakes.holding.deceleration); } - brakes.independentValveFlow = brakes.independentValve->GetPF(PulleeMode ? 0.0 : std::max(lbpa, brakes.independentPositionEim), brakes.distributor->GetBCP(), mainPipe.Pressure(), dt, 0); + brakes.independentValveFlow = brakes.independentValve->GetPF(PulleeMode ? 0.0 : std::max(lbpa, brakes.IndependentPositionEim()), brakes.distributor->GetBCP(), mainPipe.Pressure(), dt, 0); } else { @@ -911,13 +911,13 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) } else if (brakes.electrodynamic.splitFromPneumatic) // When LocHandleTimeTraxx and SplitEDPneumaticBrake are both active, lbpa is taken from LocHandleTimeTraxx, which is the desired behavior. { - lbpa = brakes.independentPosition; + lbpa = brakes.IndependentPosition(); } else { lbpa = 0.0; } - brakes.independentValveFlow = brakes.independentValve->GetPF(PulleeMode ? 0.0 : std::max(lbpa, brakes.independentPositionEim), brakes.distributor->GetBCP(), mainPipe.Pressure(), dt, 0); + brakes.independentValveFlow = brakes.independentValve->GetPF(PulleeMode ? 0.0 : std::max(lbpa, brakes.IndependentPositionEim()), brakes.distributor->GetBCP(), mainPipe.Pressure(), dt, 0); } } @@ -925,7 +925,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) void physics::Vehicle::UpdateMainValve(double dt) { auto const temp{MainValveSupply()}; - brakes.driverValve->SetReductor(brakes.handleCapPosition); + brakes.driverValve->SetReductor(brakes.HandleCapPosition()); if (PulleeMode) { @@ -935,7 +935,7 @@ void physics::Vehicle::UpdateMainValve(double dt) else if ((brakes.config.availableOperatingModes & bom_PS) == 0 || (cabOccupied != 0 && brakes.operatingMode != bom_PS)) { - if (brakes.operatingMode < bom_EP || brakes.driverValve->GetPos(bh_EB) - 0.5 < brakes.handlePositionReal || (brakes.config.driverValveType != TBrakeHandle::MHZ_EN57 && brakes.config.driverValveType != TBrakeHandle::MHZ_K8P)) + if (brakes.operatingMode < bom_EP || brakes.driverValve->GetPos(bh_EB) - 0.5 < brakes.HandlePositionReal() || (brakes.config.driverValveType != TBrakeHandle::MHZ_EN57 && brakes.config.driverValveType != TBrakeHandle::MHZ_K8P)) { brakes.driverValveFlow = brakes.driverValve->GetPF(MainValveHandlePosition(), brakePipe.Pressure(), temp, dt, brakes.equivalentPipePressure); } @@ -944,9 +944,9 @@ void physics::Vehicle::UpdateMainValve(double dt) brakes.driverValveFlow = brakes.driverValve->GetPF(0, brakePipe.Pressure(), temp, dt, brakes.equivalentPipePressure); } } - else if (brakes.handlePosition == brakes.driverValve->GetPos(bh_EB)) + else if (brakes.HandlePosition() == brakes.driverValve->GetPos(bh_EB)) { - brakes.driverValveFlow = brakes.driverValve->GetPF(brakes.handlePositionReal, brakePipe.Pressure(), temp, dt, brakes.equivalentPipePressure); + brakes.driverValveFlow = brakes.driverValve->GetPF(brakes.HandlePositionReal(), brakePipe.Pressure(), temp, dt, brakes.equivalentPipePressure); } if (brakes.driverValveFlow < 0) // && (PipePressureVal > 0.01) //50 @@ -965,7 +965,7 @@ void physics::Vehicle::UpdateMainValve(double dt) double physics::Vehicle::MainValveSupply() { brakes.pipeLock.locked = brakePipe.Pressure() < (brakes.pipeLock.locked ? brakes.pipeLock.offPressure : brakes.pipeLock.onPressure); - bool lock_new = (brakes.pipeLock.locked && !brakes.pipeLock.unlockPressed && brakes.handlePositionReal > brakes.pipeLock.unlockHandlePosition) || (brakes.config.emergencyCutsOffDriverValve && brakes.emergencyValve.flow > 0); // new simple codition based on .fiz + bool lock_new = (brakes.pipeLock.locked && !brakes.pipeLock.unlockPressed && brakes.HandlePositionReal() > brakes.pipeLock.unlockHandlePosition) || (brakes.config.emergencyCutsOffDriverValve && brakes.emergencyValve.flow > 0); // new simple codition based on .fiz bool lock_old = brakes.config.driverValveType == TBrakeHandle::FV4a // old complex condition based on assumptions && brakePipe.Pressure() < 2.75 && (brakes.distributor->GetStatus() & b_rls) == 0 && brakes.config.subsystem == TBrakeSubSystem::ss_LSt && TrainType != train_type::emu && !brakes.pipeLock.unlockPressed; @@ -979,8 +979,8 @@ double physics::Vehicle::MainValveSupply() // the position the driver's handle works at: its own, or the one the speed control's brake intervention sets double physics::Vehicle::MainValveHandlePosition() const { - double pos = brakes.handlePositionReal; - if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && brakes.handlePosition != brakes.driverValve->GetPos(bh_EB)) + double pos = brakes.HandlePositionReal(); + if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && brakes.HandlePosition() != brakes.driverValve->GetPos(bh_EB)) { pos = brakes.driverValve->GetPos(bh_NP); if (SpeedCtrlUnit.BrakeInterventionBraking) @@ -1002,7 +1002,7 @@ void physics::Vehicle::UpdateEmergencyValve(double dt) // 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 && brakes.independentPosition >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || + auto const ownemergency{radioStopFlag || (EIMCtrlEmergency && brakes.IndependentPosition() >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || (brakes.spring.driveEmergencySpeed >= 0 && Vel > brakes.spring.driveEmergencySpeed && brakes.spring.isActive) || (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)}; if (brakes.alarmChain || (ownemergency && false == PulleeMode)) diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index 7e7ca796d..36b415f3c 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -128,10 +128,10 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) } ActFlowSpeed = 0.0; - brakes.handlePositionReal = brakes.handlePosition; + brakes.SetHandlePositionReal(brakes.HandlePosition()); if (brakes.config.independentValveType == TBrakeHandle::Knorr) - brakes.independentPosition = 0.5; + brakes.SetIndependentPosition(0.5); brakePipe.reservoir->CreatePress(brakePipe.Pressure()); mainPipe.reservoir->CreatePress(mainPipe.Pressure()); @@ -424,11 +424,11 @@ void physics::Vehicle::SetReadyToDepart() mainPipe.SetPressure(InitialScndPipePress(5.0)); brakePipe.SetPressure(brakes.controlReservoirPressure); brakes.cylinderPressure = 0.0; - brakes.independentPosition = 0.0; + brakes.SetIndependentPosition(0.0); if (CabActive == 0) - brakes.handlePosition = static_cast(brakes.driverValve->GetPos(bh_NP)); + brakes.SetHandlePosition(static_cast(brakes.driverValve->GetPos(bh_NP))); else - brakes.handlePosition = static_cast(brakes.driverValve->GetPos(bh_RP)); + brakes.SetHandlePosition(static_cast(brakes.driverValve->GetPos(bh_RP))); /* // NOTE: disabled and left up to the driver, if there's any MainSwitch( false ); @@ -456,8 +456,8 @@ void physics::Vehicle::SetBraked() brakePipe.SetPressure(brakes.config.pipeLowPressure); brakes.pipeCylinderPressure = brakes.config.maxCylinderPressure[3] * 0.5; brakes.cylinderPressure = brakes.config.maxCylinderPressure[3] * 0.5; - brakes.independentPosition = 0.0; - brakes.handlePosition = static_cast(brakes.driverValve->GetPos(bh_NP)); + brakes.SetIndependentPosition(0.0); + brakes.SetHandlePosition(static_cast(brakes.driverValve->GetPos(bh_NP))); brakes.pipeLimiterPressure = brakes.config.pipeLowPressure; if (brakes.config.localKind == TLocalBrake::ManualBrake || brakes.config.hasHandBrake == true) { diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index b3b6e349a..aedc46797 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -1185,7 +1185,7 @@ void physics::Vehicle::InductionMotorDynamicBrakeFlag() brakes.electrodynamic.on = true; } else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && anPos < 0.01) || - (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && brakes.independentPosition < 0.01)) + (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && brakes.IndependentPosition() < 0.01)) brakes.electrodynamic.on = false; else if (brakes.cylinderPressure > 0.25 && edBCP > 0.25 || localbrakeforED || anPos > 0.02 || dynbrakectrlactive) brakes.electrodynamic.on = true; diff --git a/physics/consistbraking.cpp b/physics/consistbraking.cpp index a718a6624..235e9ac0c 100644 --- a/physics/consistbraking.cpp +++ b/physics/consistbraking.cpp @@ -171,7 +171,7 @@ void physics::ConsistBrakeBlending::UpdateShuntMode(Step &state, Vehicle &Lead) void physics::ConsistBrakeBlending::ComputeDemand(Step &state, Vehicle &Lead, double const dt1) { state.Fzad = state.amax * state.LBR * state.masa; - if ((Lead.brakes.handlePosition == Lead.brakes.driverValve->GetPos(bh_EB) + if ((Lead.brakes.HandlePosition() == Lead.brakes.driverValve->GetPos(bh_EB) && Lead.inductionMotor.braking.cylinderPressureGain < 0.001) || Lead.brakes.emergencyValve.flow > 0) state.Fzad = state.amax * state.masa; //pętla bezpieczeństwa - pełne służbowe @@ -243,7 +243,7 @@ void physics::ConsistBrakeBlending::ComputeElectrodynamicDemand(Step &state, Veh Lead.brakes.blending.edDelayTimer = state.FrED > 0 ? -Lead.brakes.blending.edNextDelay : -Lead.brakes.blending.edFirstDelay; } } - if (Lead.brakes.handlePosition == Lead.brakes.driverValve->GetPos(bh_EB) + if (Lead.brakes.HandlePosition() == Lead.brakes.driverValve->GetPos(bh_EB) && Lead.inductionMotor.braking.cylinderPressureGain < 0.001) state.FzadED = 0; //pętla bezpieczeństwa - bez ED state.FzadPN = state.Fzad - state.FrED * Lead.brakes.blending.edForceFactor; @@ -347,24 +347,24 @@ void physics::ConsistBrakeBlending::DistributeForces(Step &state, Vehicle const vehicle->brakes.distributor->GetFC( Nmax / (vehicle->NAxles * vehicle->brakes.config.blocksPerAxle), VelC) * 1000; // sila hamowania pn - vehicle->brakes.independentPositionEim = FzEP[i] / FmaxPoj; - if (vehicle->brakes.independentPositionEim>0.009) + vehicle->brakes.SetIndependentPositionEim(FzEP[i] / FmaxPoj); + if (vehicle->brakes.IndependentPositionEim()>0.009) if (vehicle->brakes.config.pressureToForce * vehicle->brakes.config.cylinders.leverRatio[0] * vehicle->brakes.config.maxCylinderPressure[0] != 0) { float x = (vehicle->brakes.config.cylinders.slackAdjusterForce / vehicle->brakes.config.cylinders.leverRatio[0] + vehicle->brakes.config.cylinders.springForce) / (vehicle->brakes.config.pressureToForce * vehicle->brakes.config.maxCylinderPressure[0]); - vehicle->brakes.independentPositionEim = x + (1 - x) * vehicle->brakes.independentPositionEim; + vehicle->brakes.SetIndependentPositionEim(x + (1 - x) * vehicle->brakes.IndependentPositionEim()); } else - vehicle->brakes.independentPositionEim = vehicle->brakes.independentPositionEim; + vehicle->brakes.SetIndependentPositionEim(vehicle->brakes.IndependentPositionEim()); else - vehicle->brakes.independentPositionEim = 0; + vehicle->brakes.SetIndependentPositionEim(0); if (vehicle->brakes.config.independentTraxx) { vehicle->eim_localbrake = state.eim_lb; - vehicle->brakes.independentPositionEim = std::max(vehicle->brakes.independentPositionEim, state.eim_lb); + vehicle->brakes.SetIndependentPositionEim(std::max(vehicle->brakes.IndependentPositionEim(), state.eim_lb)); } ++i; } diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 320c444f1..d5ab1df1a 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -450,8 +450,8 @@ void blackbox_recorder::write_cab() { sample.main_controller = static_cast(controlling->MainCtrlPos()); sample.scnd_controller = static_cast(controlling->ScndCtrlPos()); sample.reverser = static_cast(controlling->DirActive); - sample.train_brake = static_cast(occupied->brakes.handlePositionSmooth); - sample.local_brake = static_cast(occupied->brakes.independentPosition); + sample.train_brake = static_cast(occupied->brakes.HandlePositionSmooth()); + sample.local_brake = static_cast(occupied->brakes.IndependentPosition()); sample.brake_cylinder = static_cast(occupied->brakes.cylinderPressure); sample.brake_pipe = static_cast(occupied->brakePipe.Pressure()); sample.motor_current = static_cast(controlling->Im); @@ -485,7 +485,7 @@ void blackbox_recorder::write_cab() { sample.engine_temperature = controlling->diesel.heat.Ts; sample.speed_control_kmh = controlling->SpeedCtrl ? static_cast(controlling->SpeedCtrlUnit.DesiredVelocity) : 0.0f; sample.engine_power = static_cast(controlling->EnginePower); - sample.hand_brake = static_cast(std::clamp(occupied->brakes.handBrakePosition, -128, 127)); + sample.hand_brake = static_cast(std::clamp(occupied->brakes.HandBrakePosition(), -128, 127)); sample.brake_mode = static_cast(occupied->brakes.operatingMode); sample.horn = static_cast(occupied->WarningSignal()); sample.integrated_controller = static_cast(controlling->eimic); diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index 4c5ced5ec..da5f146c4 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -74,7 +74,7 @@ std::vector traction() { std::vector brakes() { return { - {"BrakeCtrlPos", [](auto const &M) { return M.brakes.handlePosition; }}, + {"BrakeCtrlPos", [](auto const &M) { return M.brakes.HandlePosition(); }}, {"PipePress", [](auto const &M) { return M.brakePipe.Pressure(); }}, {"BrakePress", [](auto const &M) { return M.brakes.cylinderPressure; }}, {"LocBrakePress", [](auto const &M) { return M.brakes.independentCylinderPressure; }}, @@ -94,12 +94,12 @@ std::vector air() { std::vector handles() { std::vector result{ - {"BrakeCtrlPosR", [](auto const &M) { return M.brakes.handlePositionReal; }}, + {"BrakeCtrlPosR", [](auto const &M) { return M.brakes.HandlePositionReal(); }}, {"dpMainValve", [](auto const &M) { return M.brakes.driverValveFlow; }}, {"HandleCP", [](auto const &M) { return M.brakes.driverValve->GetCP(); }}, {"HandleRP", [](auto const &M) { return M.brakes.driverValve->GetRP(); }}, {"HandleEP", [](auto const &M) { return M.brakes.driverValve->GetEP(); }}, - {"LocalBrakePosA", [](auto const &M) { return M.brakes.independentPosition; }}, + {"LocalBrakePosA", [](auto const &M) { return M.brakes.IndependentPosition(); }}, {"dpLocalValve", [](auto const &M) { return M.brakes.independentValveFlow; }}, }; for (int i = 0; i < 5; ++i) { diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index b3bf168c2..454978056 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -115,8 +115,8 @@ std::vector const &invariants() { }, [](auto const &M) { return values({{"V", M.V}, {"AccS", M.AccS}}); }}, {"hand brake applied, the wheels braked on the move", - [](auto const &M, double, auto const *) { return false == M.brakes.config.hasHandBrake || M.brakes.handBrakePosition == 0 || std::abs(M.V) < 0.5 || std::abs(M.Fb) > 0.0; }, - [](auto const &M) { return values({{"ManualBrakePos", M.brakes.handBrakePosition}, {"V", M.V}, {"Fb", M.Fb}}); }}, + [](auto const &M, double, auto const *) { return false == M.brakes.config.hasHandBrake || M.brakes.HandBrakePosition() == 0 || std::abs(M.V) < 0.5 || std::abs(M.Fb) > 0.0; }, + [](auto const &M) { return values({{"ManualBrakePos", M.brakes.HandBrakePosition()}, {"V", M.V}, {"Fb", M.Fb}}); }}, }; return rules; } diff --git a/tests/unit/test_brake_handles.cpp b/tests/unit/test_brake_handles.cpp index d37ef677b..98ca34336 100644 --- a/tests/unit/test_brake_handles.cpp +++ b/tests/unit/test_brake_handles.cpp @@ -111,7 +111,7 @@ TEST_CASE("brake handles: the local brake handle of every real vehicle") { real.run(60.0); for (auto const position : {0.25, 0.5, 1.0, 0.5, 0.0}) { trace.mark(std::format("local {:f}", position)); - real->brakes.independentPosition = position; + real->brakes.SetIndependentPosition(position); real.run(15.0); } trace.check(); diff --git a/tests/unit/test_brakes.cpp b/tests/unit/test_brakes.cpp index ed69a9a42..e83c25334 100644 --- a/tests/unit/test_brakes.cpp +++ b/tests/unit/test_brakes.cpp @@ -197,7 +197,7 @@ TEST_CASE("brakes: a wagon held by its hand brake on a gradient wakes and rolls slope.gradient = 0.01; vehicle wagon{definition::load("wagon")}; // made standing, it has the hand brake on (SetBraked()) - REQUIRE(wagon->brakes.handBrakePosition == ManualBrakePosNo); + REQUIRE(wagon->brakes.HandBrakePosition() == ManualBrakePosNo); wagon.hold_brake_pipe(5.0); wagon.run(90.0, slope); REQUIRE(wagon->brakes.cylinderPressure < 0.1); diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index e83dcc234..7de3a2bfc 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -150,7 +150,7 @@ TEST_CASE("cab: the spring brake shut off and released by hand, the ep brake's f scenario.act("handle stepped"); railbus.BrakeLevelSet(railbus.brakes.driverValve->GetPos(bh_RP)); CHECK(railbus.BrakeLevelAdd(1.0)); - CHECK(railbus.brakes.handlePosition == static_cast(railbus.brakes.driverValve->GetPos(bh_RP)) + 1); + CHECK(railbus.brakes.HandlePosition() == static_cast(railbus.brakes.driverValve->GetPos(bh_RP)) + 1); CHECK(railbus.BrakeLevelAdd(-1.0)); CHECK_FALSE(railbus.BrakeLevelAdd(-10.0)); CHECK_FALSE(railbus.BrakeLevelAdd(100.0)); diff --git a/tests/unit/test_consist_braking.cpp b/tests/unit/test_consist_braking.cpp index 921a636d9..85276f00f 100644 --- a/tests/unit/test_consist_braking.cpp +++ b/tests/unit/test_consist_braking.cpp @@ -79,8 +79,8 @@ TEST_CASE("consist braking: standing at full braking, every car brakes with its unit.step(2.0); for (auto const *car : unit.cars) { CAPTURE(car->Name); - CHECK(car->brakes.independentPositionEim > 0.0); - CHECK(car->brakes.independentPositionEim <= 1.0); + CHECK(car->brakes.IndependentPositionEim() > 0.0); + CHECK(car->brakes.IndependentPositionEim() <= 1.0); // the shunting mode (the holding brake) of the head car goes to all of them CHECK(car->ShuntMode == unit.cab().ShuntMode); } @@ -103,6 +103,6 @@ TEST_CASE("consist braking: with the controller at neutral and the train release CHECK(unit.blending.Figures()[demand] == doctest::Approx(0.0)); for (auto const *car : unit.cars) { CAPTURE(car->Name); - CHECK(car->brakes.independentPositionEim == doctest::Approx(0.0)); + CHECK(car->brakes.IndependentPositionEim() == doctest::Approx(0.0)); } } diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp index 93b0306b6..4c97ee31e 100644 --- a/tests/unit/test_crew.cpp +++ b/tests/unit/test_crew.cpp @@ -200,7 +200,7 @@ TEST_CASE("crew: a locomotive under power left by its driver stops and stays bra CHECK(eu07.MainCtrlPos() == eu07.MainCtrlNoPowerPos()); CHECK(eu07.ScndCtrlPos() == 0); - CHECK(eu07.brakes.handlePosition == static_cast(eu07.brakes.driverValve->GetPos(bh_EB))); + CHECK(eu07.brakes.HandlePosition() == static_cast(eu07.brakes.driverValve->GetPos(bh_EB))); CHECK(eu07.CabActive == 0); CHECK(eu07.CabOccupied() == 0); CHECK_FALSE(eu07.CabMaster); @@ -293,7 +293,7 @@ TEST_CASE("crew: the power an integrated handle asked for goes when the driver l CHECK(impuls->MainCtrlPos() == impuls->MainCtrlNoPowerPos()); CHECK(impuls->eimic == 0.0); CHECK(impuls->eimic_real == 0.0); - CHECK(impuls->brakes.handlePosition == static_cast(impuls->brakes.driverValve->GetPos(bh_EB))); + CHECK(impuls->brakes.HandlePosition() == static_cast(impuls->brakes.driverValve->GetPos(bh_EB))); CHECK(impuls->CabOccupied() == 0); } @@ -301,12 +301,12 @@ TEST_CASE("crew: a road vehicle left by its driver gets the brake the driver sto test::reseed_random(); vehicle bus{definition::fiz("road/man/nl293"), 40.0, "bus", 1}; REQUIRE(bus->brakes.config.kind == TBrakeSystem::Individual); - REQUIRE(bus->brakes.independentPosition == 0.0); + REQUIRE(bus->brakes.IndependentPosition() == 0.0); bus->CabActivisation(); crew::secure(bus.physics(), bus.physics()); - CHECK(bus->brakes.independentPosition == 1.0); + CHECK(bus->brakes.IndependentPosition() == 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_drivingaid.cpp b/tests/unit/test_drivingaid.cpp index 6b609b8ad..62c2d2be7 100644 --- a/tests/unit/test_drivingaid.cpp +++ b/tests/unit/test_drivingaid.cpp @@ -35,8 +35,8 @@ drivingaid::readout before(physics::Vehicle const &Physics) { drivingaid::readout result; result.throttle_first = Physics.EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * Physics.eimic_real)) : Physics.MainCtrlPos(); result.throttle_second = Physics.EIMCtrlType > 0 ? Physics.MainCtrlPos() : Physics.ScndCtrlPos(); - result.brake_first = Physics.UniCtrlIntegratedBrakeCtrl ? std::max(0.0, -100.0 * Physics.eimic_real) : Physics.brakes.handlePositionSmooth; - result.local_brake = Physics.brakes.independentPosition * LocalBrakePosNo; + result.brake_first = Physics.UniCtrlIntegratedBrakeCtrl ? std::max(0.0, -100.0 * Physics.eimic_real) : Physics.brakes.HandlePositionSmooth(); + result.local_brake = Physics.brakes.IndependentPosition() * LocalBrakePosNo; return result; } @@ -68,7 +68,7 @@ TEST_CASE("driving aid: the Vectron's ED lever shows as a negative throttle step 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->brakes.handlePositionSmooth)); + CHECK(braking.brake_first == doctest::Approx(vectron->brakes.HandlePositionSmooth())); CHECK(braking.show_local_brake); CHECK(braking.local_brake == doctest::Approx(0.0)); @@ -117,7 +117,7 @@ TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, CHECK_FALSE(braking.show_local_brake); // applied after all (the AI, or the keys), it shows - elf->brakes.independentPosition = 0.3; + elf->brakes.SetIndependentPosition(0.3); auto const applied{read(elf, elf_cab)}; CHECK(applied.show_local_brake); CHECK(applied.local_brake == doctest::Approx(3.0)); @@ -126,7 +126,7 @@ TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, 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->SetMainCtrlPos(5); - eu07->brakes.independentPosition = 0.2; + eu07->brakes.SetIndependentPosition(0.2); auto const readout{read(eu07, lever_cab)}; CHECK(readout.throttle_first == 5); CHECK(readout.throttle_second == eu07->ScndCtrlPos()); @@ -162,7 +162,7 @@ TEST_CASE("driving aid: every real vehicle with a local brake control shows the 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->SetMainCtrlPos(std::min(mainctrl, real->MainCtrlPosNo)); - real->brakes.independentPosition = localbrake; + real->brakes.SetIndependentPosition(localbrake); real->eimic_real = eimic; auto const now{read(real, lever_cab)}; auto const was{before(real.physics())}; diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index e1fa8df1e..e754f3d1b 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -311,7 +311,7 @@ void hold(elf &Unit, bool Hold) { else { position = 0.0; } - car.brakes.independentPositionEim = position; + car.brakes.SetIndependentPositionEim(position); } } diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp index 33f8bbfb5..f4aacbfc2 100644 --- a/tests/unit/test_pullee.cpp +++ b/tests/unit/test_pullee.cpp @@ -304,7 +304,7 @@ TEST_CASE("pullee: the local brake of a vehicle prepared for hauling stays relea // 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->brakes.independentPositionEim = 1.0; + driven->brakes.SetIndependentPositionEim(1.0); driven.run(20.0); if (pullee) { CHECK(driven->brakes.cylinderPressure < 0.1); @@ -329,9 +329,9 @@ TEST_CASE("pullee: entering the mode lets go of the hand brake and the spring br } SUBCASE("a unit standing with its hand brake on") { vehicle en57{definition::fiz("en57_v1/5bgb")}; - REQUIRE(en57->brakes.handBrakePosition > 0); + REQUIRE(en57->brakes.HandBrakePosition() > 0); CHECK(en57->PulleeModeSwitch(true)); - CHECK(en57->brakes.handBrakePosition == 0); + CHECK(en57->brakes.HandBrakePosition() == 0); } SUBCASE("a locomotive ready to depart, its battery on") { vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.1}; @@ -437,7 +437,7 @@ TEST_CASE("pullee: every real vehicle standing braked releases once prepared for // 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.physics()}; - CHECK(hauled.brakes.handBrakePosition == 0); + CHECK(hauled.brakes.HandBrakePosition() == 0); CHECK_FALSE(hauled.brakes.spring.activate); CHECK_FALSE(hauled.lowVoltage.IsBatteryOn()); train.run(180.0); diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index 1ef9a3256..a2a228a8a 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -136,9 +136,9 @@ vehicle::vehicle(definition const &Definition, double Velocity, std::string cons throw definition_error("parameters mismatch in the test vehicle definition"); } m_physics->SetMainCtrlPos(m_physics->MainCtrlNoPowerPos()); - m_physics->brakes.independentPosition = 0.0; + m_physics->brakes.SetIndependentPosition(0.0); if (driveractive) { - m_physics->brakes.handlePosition = static_cast(std::floor(m_physics->brakes.driverValve->GetPos(Cab == 0 ? bh_NP : bh_RP))); + m_physics->brakes.SetHandlePosition(static_cast(std::floor(m_physics->brakes.driverValve->GetPos(Cab == 0 ? bh_NP : bh_RP)))); // a driver keeps a vehicle on standby on its independent brake if (Cab != 0 && m_physics->brakes.config.localKind != TLocalBrake::ManualBrake && Velocity < 1.0) { m_physics->IncLocalBrakeLevel(LocalBrakePosNo); @@ -148,9 +148,9 @@ vehicle::vehicle(definition const &Definition, double Velocity, std::string cons } } else { - m_physics->brakes.handlePosition = static_cast(std::floor(m_physics->brakes.driverValve->GetPos(bh_NP))); + m_physics->brakes.SetHandlePosition(static_cast(std::floor(m_physics->brakes.driverValve->GetPos(bh_NP)))); } - m_physics->BrakeLevelSet(m_physics->brakes.handlePosition); + m_physics->BrakeLevelSet(m_physics->brakes.HandlePosition()); } void vehicle::step(track const &Track, double Dt) { diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index 6f87b81d3..15dc15dd2 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -73,7 +73,7 @@ void TController::Activation() } // odcięcie na zaworze maszynisty, FVel6 po drugiej stronie nie luzuje occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos(bh_NP) ); // odcięcie na zaworze maszynisty - BrakeLevelSet( occupied->brakes.handlePosition ); //ustawienie zmiennej GBH + BrakeLevelSet( occupied->brakes.HandlePosition() ); //ustawienie zmiennej GBH } // przejście AI na drugą stronę EN57, ET41 itp. // TODO: clean this up, there's lot of redundancy with physics::Vehicle::ChangeCab() and TTrain::MoveToVehicle() @@ -95,7 +95,7 @@ void TController::Activation() // TODO: investigate and resolve if necessary pVehicle->physics->SetCabOccupied(targetvehicle->physics->CabOccupied()); if( pVehicle->Mechanik ) { // not guaranteed, as target vehicle can be empty - pVehicle->Mechanik->BrakeLevelSet( pVehicle->physics->brakes.handlePosition ); + pVehicle->Mechanik->BrakeLevelSet( pVehicle->physics->brakes.HandlePosition() ); } // finish driver swap pVehicle = targetvehicle; @@ -110,7 +110,7 @@ void TController::Activation() occupied->brakes.pipeLimiterPressure = occupied->brakePipe.Pressure(); occupied->ActFlowSpeed = 0; } - BrakeLevelSet( occupied->brakes.handlePosition ); + BrakeLevelSet( occupied->brakes.HandlePosition() ); } if( mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->ShuntModeAllow ) { // dla 2Ls150 - przed ustawieniem kierunku - można zmienić tryb pracy @@ -319,13 +319,13 @@ bool TController::CheckVehicles(DriverOrders user) && p->Mechanik != this && p->Mechanik->drivingFlags.primary ) { // ale chodzi o inny pojazd, niż aktualnie sprawdzający // a tamten ma priorytet // TODO: take into account drivers' operating modes, one or more of them might be on banking duty - if (drivingFlags.primary && occupied->DirAbsolute && occupied->brakes.handlePosition >= -1) + if (drivingFlags.primary && occupied->DirAbsolute && occupied->brakes.HandlePosition() >= -1) { // jeśli rządzi i ma kierunek p->Mechanik->primary(false); // dezaktywuje tamtego p->Mechanik->ZeroLocalBrake(); p->physics->BrakeLevelSet(p->physics->brakes.driverValve->GetPos(bh_NP)); // odcięcie na zaworze maszynisty - p->Mechanik->BrakeLevelSet(p->physics->brakes.handlePosition); // ustawienie zmiennej GBH + p->Mechanik->BrakeLevelSet(p->physics->brakes.HandlePosition()); // ustawienie zmiennej GBH } else { @@ -889,7 +889,7 @@ TController::determine_consist_state() { AIControllFlag ? BrakeCtrlPosition > 0.0 : // a human driver's handle, which BrakeCtrlPosition doesn't follow - occupied->brakes.handlePositionSmooth > occupied->brakes.driverValve->GetPos( bh_RP ) + 0.2 }; + occupied->brakes.HandlePositionSmooth() > occupied->brakes.driverValve->GetPos( bh_RP ) + 0.2 }; auto const reference { brake_charge::reference( occupied->brakePipe.Pressure(), std::min( occupied->brakes.driverValve->GetRP(), 5.0 ), trainbrakeapplied ) }; // air to charge with: the engine prepared, the main reservoir above what the pipe charges to, and the driver's diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index 30f6a7e29..919d77743 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -222,7 +222,7 @@ bool TController::IncBrake() } if( occupied->EngineType == TEngineType::ElectricInductionMotor ) { if (occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_EN57) { - if (occupied->brakes.handlePosition < occupied->brakes.driverValve->GetPos(bh_FB)) + if (occupied->brakes.HandlePosition() < occupied->brakes.driverValve->GetPos(bh_FB)) OK = occupied->BrakeLevelAdd(1.0); } else { @@ -230,16 +230,16 @@ bool TController::IncBrake() } } else if( occupied->brakes.driverValve->TimeEP == false ) { - auto const initialbrakeposition { occupied->brakes.handlePositionSmooth }; + auto const initialbrakeposition { occupied->brakes.HandlePositionSmooth() }; auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], occupied->brakes.blending.maxDeceleration ) }; occupied->BrakeLevelSet( std::lerp( occupied->brakes.driverValve->GetPos( bh_EPR ), occupied->brakes.driverValve->GetPos( bh_EPB ), std::clamp( -AccDesired / AccMax * occupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); - OK = occupied->brakes.handlePositionSmooth != initialbrakeposition; + OK = occupied->brakes.HandlePositionSmooth() != initialbrakeposition; } - else if( occupied->brakes.handlePositionSmooth != occupied->brakes.driverValve->GetPos( bh_EPB ) ) { + else if( occupied->brakes.HandlePositionSmooth() != occupied->brakes.driverValve->GetPos( bh_EPB ) ) { occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_EPB ) ); if( occupied->brakes.driverValve->GetPos( bh_EPR ) - occupied->brakes.driverValve->GetPos( bh_EPN ) < 0.1 ) occupied->SwitchEPBrake( 1 ); // to nie chce działać @@ -273,8 +273,8 @@ bool TController::IncBrakeEIM() auto const brakelimit{ -2.2 * AccDesired / fMedAmax - 1.0}; //additional limit when hinted is too low auto const brakehinted{ -1.0 * occupied->AIHintLocalBrakeAccFactor * AccDesired / fMedAmax }; //preffered by AI auto const brakeposition{ maxpos * std::clamp(std::max(brakelimit, brakehinted), 0.0, 1.0)}; - OK = brakeposition != occupied->brakes.independentPosition; - occupied->brakes.independentPosition = brakeposition; + OK = brakeposition != occupied->brakes.IndependentPosition(); + occupied->brakes.SetIndependentPosition(brakeposition); } else { OK = occupied->IncLocalBrakeLevel( 1 ); @@ -383,7 +383,7 @@ bool TController::DecBrake() { case TBrakeSystem::ElectroPneumatic: { if( occupied->EngineType == TEngineType::ElectricInductionMotor ) { if( occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_EN57 ) { - if( occupied->brakes.handlePosition > occupied->brakes.driverValve->GetPos( bh_RP ) ) { + if( occupied->brakes.HandlePosition() > occupied->brakes.driverValve->GetPos( bh_RP ) ) { OK = occupied->BrakeLevelAdd( -1.0 ); } } @@ -392,18 +392,18 @@ bool TController::DecBrake() { } } else if( occupied->brakes.driverValve->TimeEP == false ) { - auto const initialbrakeposition { occupied->brakes.handlePositionSmooth }; + auto const initialbrakeposition { occupied->brakes.HandlePositionSmooth() }; auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], occupied->brakes.blending.maxDeceleration ) }; occupied->BrakeLevelSet( std::lerp( occupied->brakes.driverValve->GetPos( bh_EPR ), occupied->brakes.driverValve->GetPos( bh_EPB ), std::clamp( -AccDesired / AccMax * occupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); - OK = occupied->brakes.handlePositionSmooth != initialbrakeposition; + OK = occupied->brakes.HandlePositionSmooth() != initialbrakeposition; } else { OK = false; - if (occupied->brakes.handlePositionSmooth != occupied->brakes.driverValve->GetPos(bh_EPR)) { + if (occupied->brakes.HandlePositionSmooth() != occupied->brakes.driverValve->GetPos(bh_EPR)) { occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_EPR)); OK = true; } @@ -456,8 +456,8 @@ bool TController::DecBrakeEIM() if( occupied->brakes.blending.maxDeceleration != 9.81 ) { auto const desiredacceleration { ( occupied->Vel > EU07_AI_NOMOVEMENT ? AccDesired : std::max( 0.0, AccDesired ) ) }; auto const brakeposition { std::clamp( -1.0 * occupied->AIHintLocalBrakeAccFactor * desiredacceleration / occupied->brakes.blending.maxDeceleration, 0.0, 1.0 ) }; - OK = brakeposition != occupied->brakes.independentPosition; - occupied->brakes.independentPosition = brakeposition; + OK = brakeposition != occupied->brakes.IndependentPosition(); + occupied->brakes.SetIndependentPosition(brakeposition); } else { OK = occupied->DecLocalBrakeLevel( 1 ); @@ -1176,7 +1176,7 @@ void TController::SetTimeControllers() } */ if( occupied->UniCtrlIntegratedLocalBrakeCtrl - && occupied->brakes.independentPosition > 0.95 ) { + && occupied->brakes.IndependentPosition() > 0.95 ) { while( IncBrakeEIM() ) { ; } } diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index 10c24d013..3bb5d68f9 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -181,7 +181,7 @@ bool TController::PrepareEngine() { static_cast( occupied->brakes.driverValve->GetPos( bh_RP ) ), gbh_RP }, { static_cast( occupied->brakes.driverValve->GetPos( bh_NP ) ), gbh_NP }, { static_cast( occupied->brakes.driverValve->GetPos( bh_FS ) ), gbh_FS } }; - auto const lookup{ brakepositions.find( static_cast( occupied->brakes.handlePositionSmooth ) ) }; + auto const lookup{ brakepositions.find( static_cast( occupied->brakes.HandlePositionSmooth() ) ) }; if( lookup != brakepositions.end() ) { BrakeLevelSet( lookup->second ); // GBH } @@ -191,7 +191,7 @@ bool TController::PrepareEngine() // standing: the locomotive brake first, then the pipe is filled secure_standing_train(); } - else if( ( occupied->brakes.handlePositionSmooth != occupied->brakes.driverValve->GetPos( bh_RP ) ) + else if( ( occupied->brakes.HandlePositionSmooth() != occupied->brakes.driverValve->GetPos( bh_RP ) ) && ( ( false == occupied->brakes.driverValve->Time ) || ( occupied->brakes.driverValve->GetCP() < occupied->brakes.config.pipeHighPressure - 0.05 ) ) ) { cue_action( driver_hint::trainbrakerelease ); diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp index 242a98a80..70fdb5a36 100644 --- a/vehicle/ai/force.cpp +++ b/vehicle/ai/force.cpp @@ -95,7 +95,7 @@ TController::control_tractive_and_braking_force() { control_braking_force(); #if LOGVELOCITY - WriteLog("BrakePos=" + AnsiString(occupied->brakes.handlePosition) + ", MainCtrl=" + + WriteLog("BrakePos=" + AnsiString(occupied->brakes.HandlePosition()) + ", MainCtrl=" + AnsiString(mvControlling->MainCtrlPos())); #endif } @@ -253,7 +253,7 @@ void TController::control_uphill_start() { return; } if( ( occupied->brakes.config.localKind != TLocalBrake::ManualBrake ) - && ( occupied->brakes.independentPosition > 0.0 ) ) { + && ( occupied->brakes.IndependentPosition() > 0.0 ) ) { cue_action( driver_hint::independentbrakerelease ); } if( uphill_start::power_holds( now, ElapsedTime - uphillStart.startTime ) ) { @@ -522,7 +522,7 @@ void TController::control_braking_force() { || ( false == brake_charge::release_waits( IsConsistCharged, occupied->Vel < EU07_AI_NOMOVEMENT, - occupied->brakes.handlePositionSmooth > occupied->brakes.driverValve->GetPos( bh_RP ) + 0.2 ) ) ) ) { // the human driver's handle + occupied->brakes.HandlePositionSmooth() > occupied->brakes.driverValve->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 @@ -534,7 +534,7 @@ void TController::control_braking_force() { // uphill, the locomotive brake acts at once while the train brake of a long train takes many seconds to apply: // put it on as the train comes to a stand, and at once if the train has started to roll back if( ( occupied->brakes.config.localKind != TLocalBrake::ManualBrake ) - && ( occupied->brakes.independentPosition < 1.0 ) + && ( occupied->brakes.IndependentPosition() < 1.0 ) && ( ( uphill_stop_hold() && ( std::abs( velocity ) < 3.0 ) // a train that has slowed down short of where it is to stop and is to pull up further does not get it && ( VelDesired <= std::abs( velocity ) + 0.5 ) @@ -544,7 +544,7 @@ void TController::control_braking_force() { } // stop-gap measure to ensure cars actually brake to stop even when above calculactions go awry // instead of releasing the brakes and creeping into obstacle at 1-2 km/h - if( is_car() && VelDesired == 0.0 && velocity > VelDesired && ActualProximityDist <= fMinProximityDist && occupied->brakes.independentPosition < 0.01 ) { + if( is_car() && VelDesired == 0.0 && velocity > VelDesired && ActualProximityDist <= fMinProximityDist && occupied->brakes.IndependentPosition() < 0.01 ) { cue_action(driver_hint::brakingforceincrease); } } @@ -569,7 +569,7 @@ void TController::apply_independent_brake_only() { if( occupied->brakes.config.localKind != TLocalBrake::ManualBrake ) { if( false == occupied->ShuntMode // no need for independent brake if autobrake is active - && is_equal(occupied->brakes.handlePositionSmooth, occupied->brakes.driverValve->GetPos(bh_RP), 0.2) ) { + && is_equal(occupied->brakes.HandlePositionSmooth(), occupied->brakes.driverValve->GetPos(bh_RP), 0.2) ) { cue_action( driver_hint::independentbrakeapply ); } else { diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp index 08a40f14a..83ad149e4 100644 --- a/vehicle/ai/physicslog.cpp +++ b/vehicle/ai/physicslog.cpp @@ -77,8 +77,8 @@ std::string TController::physicslog_line() const { << mvControlling->Im << " " << int(mvControlling->MainCtrlPos()) << " " << int(mvControlling->ScndCtrlPos()) << " " - << occupied->brakes.handlePositionSmooth << " " - << occupied->brakes.independentPosition << " " + << occupied->brakes.HandlePositionSmooth() << " " + << occupied->brakes.IndependentPosition() << " " << int(mvControlling->DirActive) << " " << ( occupied->CommandIn.Text.empty() ? "none" : occupied->CommandIn.Text.c_str() ) << " " << occupied->CommandIn.Value1 << " " diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index ed4938226..01e98e40b 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -56,7 +56,7 @@ TController::update_timers( double dt ) { WaitingTime += dt; fBrakeTime -= dt; // wpisana wartość jest zmniejszana do 0, gdy ujemna należy zmienić nastawę hamulca fBrakeHeldTime += dt; - if( occupied->brakes.handlePositionSmooth != occupied->brakes.driverValve->GetPos( bh_FS ) ) { + if( occupied->brakes.HandlePositionSmooth() != occupied->brakes.driverValve->GetPos( bh_FS ) ) { // brake charging timeout starts after charging ends BrakeChargingCooldown += dt; } diff --git a/vehicle/ai/speed.cpp b/vehicle/ai/speed.cpp index 550b8819e..1f1a1d343 100644 --- a/vehicle/ai/speed.cpp +++ b/vehicle/ai/speed.cpp @@ -507,7 +507,7 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { BrakeCtrlPosition, // IncLocalBrakeLevel() moves the independent brake handle on a vehicle without one too ( occupied->brakes.config.localKind == TLocalBrake::PneumaticBrake || occupied->brakes.config.localKind == TLocalBrake::HydraulicBrake ) ? - occupied->brakes.independentPosition : + occupied->brakes.IndependentPosition() : 0.0 ), vehicle_ai::brake_response_horizon( occupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), vehicle_ai::brake_response_horizon( occupied, BrakeSystem, 1.0, fillbrakea0 ) }; diff --git a/vehicle/cab/brakecommands.cpp b/vehicle/cab/brakecommands.cpp index 1528887c9..3d5cb341c 100644 --- a/vehicle/cab/brakecommands.cpp +++ b/vehicle/cab/brakecommands.cpp @@ -112,9 +112,9 @@ void TTrain::OnCommand_independentbrakedecrease(TTrain *Train, command_data cons if (Train->occupied->brakes.config.localKind != TLocalBrake::ManualBrake // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba // TODO: sort AI out so it doesn't do things it doesn't have equipment for - || Train->occupied->brakes.independentPosition > 0) + || Train->occupied->brakes.IndependentPosition() > 0) { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->brakes.independentPosition == 0.0) + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->brakes.IndependentPosition() == 0.0) { OnCommand_mastercontrollerincrease(Train, Command); } @@ -141,9 +141,9 @@ void TTrain::OnCommand_independentbrakedecreasefast(TTrain *Train, command_data if (Train->occupied->brakes.config.localKind != TLocalBrake::ManualBrake // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba // TODO: sort AI out so it doesn't do things it doesn't have equipment for - || Train->occupied->brakes.independentPosition > 0) + || Train->occupied->brakes.IndependentPosition() > 0) { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->brakes.independentPosition == 0.0) + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->brakes.IndependentPosition() == 0.0) { OnCommand_mastercontrollerincreasefast(Train, Command); } @@ -165,7 +165,7 @@ void TTrain::OnCommand_independentbrakeset(TTrain *Train, command_data const &Co if (Command.action != GLFW_RELEASE) { - Train->occupied->brakes.independentPosition = std::clamp(Command.param1, 0.0, 1.0); + Train->occupied->brakes.SetIndependentPosition(std::clamp(Command.param1, 0.0, 1.0)); } /* Train->controlled->LocalBrakePos = ( @@ -298,7 +298,7 @@ void TTrain::OnCommand_trainbrakeincrease(TTrain *Train, command_data const &Com if (Command.action == GLFW_REPEAT && Train->occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) Train->occupied->BrakeLevelAdd(Global.brake_speed * Command.time_delta * Train->occupied->brakes.config.handlePositions); else if (Command.action == GLFW_PRESS && Train->occupied->brakes.config.driverValveType != TBrakeHandle::FV4a) - Train->set_train_brake(Train->occupied->brakes.handlePositionSmooth + Global.fBrakeStep); + Train->set_train_brake(Train->occupied->brakes.HandlePositionSmooth() + Global.fBrakeStep); } void TTrain::OnCommand_trainbrakedecrease(TTrain *Train, command_data const &Command) @@ -306,7 +306,7 @@ void TTrain::OnCommand_trainbrakedecrease(TTrain *Train, command_data const &Com if (Command.action == GLFW_REPEAT && Train->occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) Train->occupied->BrakeLevelAdd(-Global.brake_speed * Command.time_delta * Train->occupied->brakes.config.handlePositions); else if (Command.action == GLFW_PRESS && Train->occupied->brakes.config.driverValveType != TBrakeHandle::FV4a) - Train->set_train_brake(Train->occupied->brakes.handlePositionSmooth - Global.fBrakeStep); + Train->set_train_brake(Train->occupied->brakes.HandlePositionSmooth() - Global.fBrakeStep); else if (Command.action == GLFW_RELEASE) { // release @@ -418,7 +418,7 @@ void TTrain::OnCommand_trainbrakebasepressureincrease(TTrain *Train, command_dat if (Train->occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) { - Train->occupied->brakes.handleCapPosition = std::clamp(Train->occupied->brakes.handleCapPosition - 0.01, -1.5, 2.0); + Train->occupied->brakes.SetHandleCapPosition(std::clamp(Train->occupied->brakes.HandleCapPosition() - 0.01, -1.5, 2.0)); } else { @@ -435,7 +435,7 @@ void TTrain::OnCommand_trainbrakebasepressuredecrease(TTrain *Train, command_dat if (Train->occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) { - Train->occupied->brakes.handleCapPosition = std::clamp(Train->occupied->brakes.handleCapPosition + 0.01, -1.5, 2.0); + Train->occupied->brakes.SetHandleCapPosition(std::clamp(Train->occupied->brakes.HandleCapPosition() + 0.01, -1.5, 2.0)); } else { @@ -450,7 +450,7 @@ void TTrain::OnCommand_trainbrakebasepressurereset(TTrain *Train, command_data c if (Command.action == GLFW_PRESS) { - Train->occupied->brakes.handleCapPosition = 0; + Train->occupied->brakes.SetHandleCapPosition(0); } } diff --git a/vehicle/cab/controllercommands.cpp b/vehicle/cab/controllercommands.cpp index a25bc797e..b02129e65 100644 --- a/vehicle/cab/controllercommands.cpp +++ b/vehicle/cab/controllercommands.cpp @@ -97,7 +97,7 @@ void TTrain::OnCommand_jointcontrollerset(TTrain *Train, command_data const &Com } else { - Train->occupied->brakes.independentPosition = 0; + Train->occupied->brakes.SetIndependentPosition(0); } } else @@ -113,7 +113,7 @@ void TTrain::OnCommand_jointcontrollerset(TTrain *Train, command_data const &Com } else { - Train->occupied->brakes.independentPosition = negativeRange; + Train->occupied->brakes.SetIndependentPosition(negativeRange); } if (Train->controlled->MainCtrlPowerPos() > 0) { @@ -138,7 +138,7 @@ void TTrain::OnCommand_mastercontrollerincrease(TTrain *Train, command_data cons auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; // when SplitEDPneumaticBrake is true the joint controller's negative range maps // to the dedicated dynamic-brake lever (DynamicBrakeCtrl) rather than to LocalBrake - auto const negativeRangeActive{splitMode ? Train->controlled->brakes.electrodynamic.controllerPosition > 0.0 : Train->occupied->brakes.independentPosition > 0.0}; + auto const negativeRangeActive{splitMode ? Train->controlled->brakes.electrodynamic.controllerPosition > 0.0 : Train->occupied->brakes.IndependentPosition() > 0.0}; if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) { if (splitMode) @@ -172,7 +172,7 @@ void TTrain::OnCommand_mastercontrollerincreasefast(TTrain *Train, command_data { // on press or hold auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; - auto const negativeRangeActive{splitMode ? Train->controlled->brakes.electrodynamic.controllerPosition > 0.0 : Train->occupied->brakes.independentPosition > 0.0}; + auto const negativeRangeActive{splitMode ? Train->controlled->brakes.electrodynamic.controllerPosition > 0.0 : Train->occupied->brakes.IndependentPosition() > 0.0}; if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) { if (splitMode) diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index 65a9be482..ae1add60b 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -1676,8 +1676,8 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con } } // TODO: move viable dedicated gauges to the automatic array - std::unordered_map const autointgauges = { - {"manualbrake:", &occupied->brakes.handBrakePosition}, + std::unordered_map const autointgauges = { + {"manualbrake:", &occupied->brakes.HandBrakePosition()}, {"pantselect_sw:", &occupied->pantographCircuit.presets.second[cab_to_end()]}, }; { diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 909d44531..9d9df0c45 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -214,15 +214,15 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("scndctrl_pos", controlled->ScndCtrlPos()); dict->insert("dynamicbrake_pos", controlled->brakes.electrodynamic.controllerPosition); dict->insert("scnd_ctrl_actual_pos", controlled->ScndCtrlActualPos); - dict->insert("brakectrl_pos", controlled->brakes.handlePositionSmooth); - dict->insert("localbrake_pos", controlled->brakes.independentPosition); + dict->insert("brakectrl_pos", controlled->brakes.HandlePositionSmooth()); + dict->insert("localbrake_pos", controlled->brakes.IndependentPosition()); dict->insert("new_speed", occupied->NewSpeed); dict->insert("speedctrl", occupied->SpeedCtrlValue); dict->insert("speedctrlpower", occupied->SpeedCtrlUnit.DesiredPower); dict->insert("speedctrlactive", occupied->SpeedCtrlUnit.IsActive); dict->insert("speedctrlstandby", occupied->SpeedCtrlUnit.Standby); // brakes - dict->insert("manual_brake", occupied->brakes.handBrakePosition > 0); + dict->insert("manual_brake", occupied->brakes.HandBrakePosition() > 0); bool const bEP = controlled->brakes.independentValve->GetCP() > 0.2 || fEIMParams[0][5] > 0.01; dict->insert("dir_brake", bEP); bool bPN{false}; @@ -463,16 +463,16 @@ void TTrain::set_master_controller(double const Position) void TTrain::set_train_brake(double const Position) { - auto const originalbrakeposition{static_cast(100.0 * occupied->brakes.handlePositionSmooth)}; + auto const originalbrakeposition{static_cast(100.0 * occupied->brakes.HandlePositionSmooth())}; occupied->BrakeLevelSet(Position); - if (static_cast(100.0 * occupied->brakes.handlePositionSmooth) == originalbrakeposition) + if (static_cast(100.0 * occupied->brakes.HandlePositionSmooth()) == originalbrakeposition) { return; } // sound feedback if the lever movement activates one of the switches - if (true == is_eztoer() && false == ((originalbrakeposition / 100 == 0 || originalbrakeposition / 100 >= 5) && (occupied->brakes.handlePosition == 0 || occupied->brakes.handlePosition >= 5)) && dsbPneumaticSwitch) + if (true == is_eztoer() && false == ((originalbrakeposition / 100 == 0 || originalbrakeposition / 100 >= 5) && (occupied->brakes.HandlePosition() == 0 || occupied->brakes.HandlePosition() >= 5)) && dsbPneumaticSwitch) { dsbPneumaticSwitch->play(); } @@ -482,7 +482,7 @@ void TTrain::zero_charging_train_brake() { using enum TBrakeHandle; - if (occupied->brakes.handlePosition == -1 && DynamicObject->Controller != AIdriver && Global.iFeedbackMode < 3 && + if (occupied->brakes.HandlePosition() == -1 && DynamicObject->Controller != AIdriver && Global.iFeedbackMode < 3 && (occupied->brakes.config.driverValveType == FVel6 || occupied->brakes.config.driverValveType == MHZ_EN57 || occupied->brakes.config.driverValveType == MHZ_K8P)) { // Odskakiwanie hamulce EP diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 257b0efcc..61d9dd681 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -920,7 +920,7 @@ void TTrain::updateTrainLamps() btLampkaRadio.Turn(occupied->Radio() && occupied->RadioFuse()); btLampkaRadioMessage.Turn(radio_message_played); btLampkaRadioStop.Turn(occupied->Radio() && occupied->RadioFuse() && occupied->RadioStopFlag()); - btLampkaHamulecReczny.Turn(occupied->brakes.handBrakePosition > 0); + btLampkaHamulecReczny.Turn(occupied->brakes.HandBrakePosition() > 0); // NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu if (DynamicObject->Mechanik != nullptr) { @@ -1191,7 +1191,7 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) // represents the dedicated dynamic-brake lever (DBPN steps), not the pneumatic local brake auto const negativePart{controlled->brakes.electrodynamic.splitFromPneumatic ? (controlled->brakes.electrodynamic.controllerPosition > 0.0 ? controlled->brakes.electrodynamic.controllerPosition * controlled->brakes.electrodynamic.controllerPositions * -1 * brakerangemultiplier : 0.0) : - occupied->brakes.independentPosition > 0.0 ? occupied->brakes.independentPosition * LocalBrakePosNo * -1 * brakerangemultiplier : + occupied->brakes.IndependentPosition() > 0.0 ? occupied->brakes.IndependentPosition() * LocalBrakePosNo * -1 * brakerangemultiplier : 0.0}; ggJointCtrl.UpdateValue(negativePart < 0.0 ? static_cast(negativePart) : controlled->CoupledCtrl ? static_cast(double(controlled->MainCtrlPos() + controlled->ScndCtrlPos())) : @@ -1306,7 +1306,7 @@ void TTrain::updateBrakeControllers() { // else //standardowa prodedura z kranem powiązanym z klawiaturą // ggBrakeCtrl.UpdateValue(double(occupied->BrakeCtrlPos)); - ggBrakeCtrl.UpdateValue(static_cast(occupied->brakes.handlePositionSmooth)); + ggBrakeCtrl.UpdateValue(static_cast(occupied->brakes.HandlePositionSmooth())); ggBrakeCtrl.Update(); } } @@ -1320,14 +1320,14 @@ void TTrain::updateBrakeControllers() // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba // Firleju: dlatego kasujemy i zastepujemy funkcją w Console auto const b = std::clamp(Console::AnalogCalibrateGet(1), 0.f, 1.f); - occupied->brakes.independentPosition = b; + occupied->brakes.SetIndependentPosition(b); ggLocalBrake.UpdateValue(b * LocalBrakePosNo); } else #endif { // standardowa prodedura z kranem powiązanym z klawiaturą - ggLocalBrake.UpdateValue(static_cast(occupied->brakes.independentPosition * LocalBrakePosNo)); + ggLocalBrake.UpdateValue(static_cast(occupied->brakes.IndependentPosition() * LocalBrakePosNo)); } ggLocalBrake.Update(); } diff --git a/vehicle/drivingaid.cpp b/vehicle/drivingaid.cpp index d0ecb2c15..15c68faa0 100644 --- a/vehicle/drivingaid.cpp +++ b/vehicle/drivingaid.cpp @@ -70,8 +70,8 @@ input from_vehicles(physics::Vehicle const &Vehicle, physics::Vehicle const &Con result.dynamicbrakeposno = Controlling.brakes.electrodynamic.controllerPositions; result.mainctrlpos = Controlling.MainCtrlPos(); result.scndctrlpos = Controlling.ScndCtrlPos(); - result.brakectrlpos = Vehicle.brakes.handlePositionSmooth; - result.localbrakepos = Vehicle.brakes.independentPosition; + result.brakectrlpos = Vehicle.brakes.HandlePositionSmooth(); + result.localbrakepos = Vehicle.brakes.IndependentPosition(); result.cab = Cab; return result; } diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index 3af162884..64416967f 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -264,14 +264,13 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" // controller position physics->SetMainCtrlPos(physics->MainCtrlNoPowerPos()); // ustawienie pozycji hamulca - physics->brakes.independentPosition = 0.0; + physics->brakes.SetIndependentPosition(0.0); if (driveractive) { if (Cab == 0) - physics->brakes.handlePosition = - static_cast( std::floor(physics->brakes.driverValve->GetPos(bh_NP)) ); + physics->brakes.SetHandlePosition(static_cast( std::floor(physics->brakes.driverValve->GetPos(bh_NP)) )); else - physics->brakes.handlePosition = static_cast( std::floor(physics->brakes.driverValve->GetPos(bh_RP)) ); + physics->brakes.SetHandlePosition(static_cast( std::floor(physics->brakes.driverValve->GetPos(bh_RP)) )); // engage independent brake if applicable, if the vehicle is to be on standby // NOTE: with more than one driver in the consist this is likely to go awery, since all but one will be sent to sleep @@ -288,12 +287,11 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" } } else - physics->brakes.handlePosition = - static_cast( std::floor(physics->brakes.driverValve->GetPos(bh_NP)) ); + physics->brakes.SetHandlePosition(static_cast( std::floor(physics->brakes.driverValve->GetPos(bh_NP)) )); // poprawienie hamulca po ewentualnym przestawieniu przez Pascal // TODO: check if needed, we're not in Pascal anymore, Toto - physics->BrakeLevelSet(physics->brakes.handlePosition); + physics->BrakeLevelSet(physics->brakes.HandlePosition()); // dodatkowe parametry yB MoreParams += "."; // wykonuje o jedną iterację za mało, więc trzeba mu dodać diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index 778b2163b..e5bccba88 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -260,7 +260,7 @@ void TDynamicObject::renderEpBrakeSounds( double const dt ) { if (physics->brakes.config.kind == TBrakeSystem::ElectroPneumatic && physics->brakes.independentValve) { auto const epbrakepressureratio{ std::min( std::max( 0.0, physics->brakes.independentValve->GetCP() ) / std::max( 1.0, physics->brakes.config.maxCylinderPressure[0] ), m_epbrakepressurechangedectimer > -1.0f ? - std::max( physics->brakes.independentPositionEim, physics->brakes.distributor->GetEDBCP() / physics->brakes.config.maxCylinderPressure[3]) : + std::max( physics->brakes.IndependentPositionEim(), physics->brakes.distributor->GetEDBCP() / physics->brakes.config.maxCylinderPressure[3]) : 1.0 ) }; if ( m_lastepbrakepressure != -1.f ) { // HACK: potentially reset playback of opening bookend sounds @@ -296,7 +296,7 @@ void TDynamicObject::renderEpBrakeSounds( double const dt ) { } if ( m_epbrakepressurechangeinctimer == 0 || m_epbrakepressurechangedectimer == 0 ) m_lastepbrakepressure = std::min( physics->brakes.independentValve->GetCP(), - physics->brakes.independentPositionEim * std::max( 1.0, physics->brakes.config.maxCylinderPressure[0] ) ); + physics->brakes.IndependentPositionEim() * std::max( 1.0, physics->brakes.config.maxCylinderPressure[0] ) ); } } diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index b80cb28a7..8d786f02b 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -201,11 +201,11 @@ void ui::vehicleparams_panel::render_contents() STR_C("Brakes:\n train: %.2f, independent: %.2f, mode: %d, delay: %s, load flag: %d\nBrake cylinder pressures:\n train: %.2f, independent: %.2f, status: 0x%.2x\nPipe pressures:\n " "brake: %.2f (hat: %.2f), main: %.2f, control: %.2f\nTank pressures:\n auxiliary: %.2f, main: %.2f, control: %.2f"), // brakes - physics.brakes.handlePositionSmooth, physics.brakes.independentPosition, physics.brakes.operatingMode, brakedelay.c_str(), physics.brakes.loadSetting, + physics.brakes.HandlePositionSmooth(), physics.brakes.IndependentPosition(), physics.brakes.operatingMode, brakedelay.c_str(), physics.brakes.loadSetting, // cylinders physics.brakes.cylinderPressure, physics.brakes.independentCylinderPressure, physics.brakes.distributor->GetBrakeStatus(), // pipes - physics.brakePipe.Pressure(), physics.brakes.handleCapPosition, physics.mainPipe.Pressure(), physics.brakes.controlReservoirPressure, + physics.brakePipe.Pressure(), physics.brakes.HandleCapPosition(), physics.mainPipe.Pressure(), physics.brakes.controlReservoirPressure, // tanks physics.brakes.distributor->GetBRP(), physics.air.MainReservoirPressure(), physics.brakes.distributor->GetCRP()); From f65411a66893b73fa929d48a16c896f571fc5179 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 12:43:38 +0100 Subject: [PATCH 23/30] refactor(physics): the motion of the vehicle is private to it The speed along the couplers, the location, the offsets from the track axis, the accelerations, the distance counter and the distance moved since the last check, the flat of the wheels and the truck hunting, the distance of the derailment check, whether the vehicle is inside a consist and in the coupler model, the analog demand of the integrated controller and the flow of the pipe stabiliser are private to physics::Vehicle. TDynamicObject places and moves the vehicle, the scenery puts road vehicles on their way and the contacts push them through the operations (SetV(), SetLoc(), SetOffsetTrackH(), ...), and the jolts of the track are ShakeVertically() and ShakeHorizontally(), the same additions as before. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- application/driveruipanels.cpp | 18 +-- input/messaging.cpp | 16 +-- physics/components/body.cpp | 140 +++++++++++------------ physics/components/cab.cpp | 4 +- physics/components/collisions.cpp | 42 +++---- physics/components/commands.cpp | 4 +- physics/components/controllers.cpp | 2 +- physics/components/couplers.cpp | 16 +-- physics/components/diesel.cpp | 8 +- physics/components/securitysystem.cpp | 2 +- physics/components/setup.cpp | 2 +- physics/components/traction.cpp | 12 +- physics/consistbraking.cpp | 2 +- physics/vehicle.h | 75 +++++++++--- simulation/blackboxrecorder.cpp | 12 +- simulation/simulation.cpp | 8 +- tests/unit/consist.cpp | 6 +- tests/unit/figures.cpp | 8 +- tests/unit/golden.cpp | 8 +- tests/unit/invariants.cpp | 20 ++-- tests/unit/invariants.h | 4 +- tests/unit/test_cab.cpp | 2 +- tests/unit/test_collisions.cpp | 20 ++-- tests/unit/test_commands.cpp | 10 +- tests/unit/test_consist.cpp | 2 +- tests/unit/test_consist_braking.cpp | 2 +- tests/unit/test_controls.cpp | 8 +- tests/unit/test_coupler_physics.cpp | 4 +- tests/unit/test_derail_motion.cpp | 8 +- tests/unit/test_derailment_vehicle.cpp | 38 +++--- tests/unit/test_dynamic_brake_diesel.cpp | 8 +- tests/unit/test_figures.cpp | 6 +- tests/unit/test_genset.cpp | 10 +- tests/unit/test_invariants.cpp | 2 +- tests/unit/test_odometer.cpp | 4 +- tests/unit/test_queries.cpp | 2 +- tests/unit/test_traction.cpp | 2 +- tests/unit/vehicle.cpp | 2 +- tests/unit/vehicle.h | 2 +- utilities/motiontelemetry.cpp | 6 +- utilities/uart.cpp | 2 +- vehicle/ai/consist.cpp | 10 +- vehicle/ai/driver.cpp | 4 +- vehicle/ai/engine.cpp | 2 +- vehicle/ai/obstacles.cpp | 6 +- vehicle/ai/orders.cpp | 10 +- vehicle/ai/physicslog.cpp | 6 +- vehicle/ai/routescan.cpp | 2 +- vehicle/ai/situation.cpp | 2 +- vehicle/ai/speedtable.cpp | 4 +- vehicle/cab/cabcommands.cpp | 4 +- vehicle/cab/train.cpp | 4 +- vehicle/cab/update.cpp | 2 +- vehicle/dynamic/consist.cpp | 8 +- vehicle/dynamic/couplers.cpp | 4 +- vehicle/dynamic/lifecycle.cpp | 21 ++-- vehicle/dynamic/lights.cpp | 2 +- vehicle/dynamic/movement.cpp | 10 +- vehicle/dynamic/neighbours.cpp | 4 +- vehicle/dynamic/offtrack.cpp | 14 +-- vehicle/dynamic/sounds.cpp | 8 +- vehicle/dynamic/update.cpp | 21 ++-- vehicle/dynamic/vehicletable.cpp | 14 +-- vehicle/dynamic/visual.cpp | 8 +- widgets/trainingcard.cpp | 2 +- widgets/vehicleparams.cpp | 6 +- world/Road.cpp | 2 +- world/RoadPoint.cpp | 6 +- 68 files changed, 387 insertions(+), 348 deletions(-) diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index e474514f4..81bc2bdf9 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -806,7 +806,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.LoadType.name.c_str(), physics.EngineDescription( 0 ).c_str(), // TODO: put wheel flat reporting in the enginedescription() - std::string( physics.WheelFlat > 0.01 ? " Flat: " + to_string( physics.WheelFlat, 1 ) + " mm" : "" ).c_str(), + std::string( physics.WheelFlat() > 0.01 ? " Flat: " + to_string( physics.WheelFlat(), 1 ) + " mm" : "" ).c_str(), update_vehicle_coupler( VehicleEnd::front ).c_str(), update_vehicle_coupler( VehicleEnd::rear ).c_str() ); @@ -968,11 +968,11 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.SlippingWheels ? " (!)" : "", // acceleration physics.AccSVBased, - physics.AccN + 0.001f, + physics.AccN() + 0.001f, std::string( std::abs( physics.RunningShape.R ) > 15000.0 ? "~0" : to_string( physics.RunningShape.R, 0 ) ).c_str(), // velocity vehicle.GetVelocity(), - physics.DistCounter, + physics.DistCounter(), // position vehicle.GetPosition().x, vehicle.GetPosition().y, @@ -1007,11 +1007,11 @@ debug_panel::update_section_vehicle( std::vector &Output ) { if (!std::isnan(last_time)) { double dt = Timer::GetTime() - last_time; - AccN_jerk_graph.update(static_cast((physics.AccN - last_AccN) / dt)); - AccN_acc_graph.update(static_cast(physics.AccN)); + AccN_jerk_graph.update(static_cast((physics.AccN() - last_AccN) / dt)); + AccN_acc_graph.update(static_cast(physics.AccN())); } - last_AccN = static_cast(physics.AccN); + last_AccN = static_cast(physics.AccN()); last_time = Timer::GetTime(); } @@ -1123,8 +1123,8 @@ debug_panel::update_section_engine( std::vector &Output ) const { if( physics.EngineType == TEngineType::DieselEngine ) { double fuel_mean = 0.0; - if (physics.DistCounter > 0.5) { - fuel_mean = 100 * physics.diesel.fuelConsumedTotal / physics.DistCounter; + if (physics.DistCounter() > 0.5) { + fuel_mean = 100 * physics.diesel.fuelConsumedTotal / physics.DistCounter(); } std::string parameterstext = "param value"; @@ -1629,7 +1629,7 @@ debug_panel::update_section_coupler( std::vector &Output ) { "Model: {} (couplerphysics {}, vehicle {}covered), crash damage {}", physics.coupler_physics_at( m_coupler.end ) ? "physical" : "legacy", coupler_physics_setting(), - physics.CouplerPhysics ? "" : "not ", + physics.CouplerPhysics() ? "" : "not ", Global.crash_damage ? "on" : "off" ), Global.UITextColor ); if( neighbour.vehicle != nullptr ) { diff --git a/input/messaging.cpp b/input/messaging.cpp index 5d0489363..ce52e718d 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -273,17 +273,17 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) size_t j = Vehicle->asName.length(); r.iPar[0] = i; // ilość danych liczbowych r.fPar[1] = Global.fTimeAngleDeg / 360.0; // aktualny czas (1.0=doba) - r.fPar[2] = Vehicle->physics->Loc.X; // pozycja X - r.fPar[3] = Vehicle->physics->Loc.Y; // pozycja Y - r.fPar[4] = Vehicle->physics->Loc.Z; // pozycja Z - r.fPar[5] = Vehicle->physics->V; // prędkość ruchu X + r.fPar[2] = Vehicle->physics->Loc().X; // pozycja X + r.fPar[3] = Vehicle->physics->Loc().Y; // pozycja Y + r.fPar[4] = Vehicle->physics->Loc().Z; // pozycja Z + r.fPar[5] = Vehicle->physics->V(); // prędkość ruchu X r.fPar[6] = Vehicle->physics->nrot * M_PI * Vehicle->physics->WheelDiameter; // prędkość obrotowa kóŁ r.fPar[7] = 0; // prędkość ruchu Z - r.fPar[8] = Vehicle->physics->AccS; // przyspieszenie X - r.fPar[9] = Vehicle->physics->AccN; // przyspieszenie Y //na razie nie - r.fPar[10] = Vehicle->physics->AccVert; // przyspieszenie Z - r.fPar[11] = Vehicle->physics->DistCounter; // przejechana odległość w km + r.fPar[8] = Vehicle->physics->AccS(); // przyspieszenie X + r.fPar[9] = Vehicle->physics->AccN(); // przyspieszenie Y //na razie nie + r.fPar[10] = Vehicle->physics->AccVert(); // przyspieszenie Z + r.fPar[11] = Vehicle->physics->DistCounter(); // przejechana odległość w km r.fPar[12] = Vehicle->physics->brakePipe.Pressure(); // ciśnienie w PG r.fPar[13] = Vehicle->physics->mainPipe.Pressure(); // ciśnienie w PZ r.fPar[14] = Vehicle->physics->brakes.cylinderPressure; // ciśnienie w CH diff --git a/physics/components/body.cpp b/physics/components/body.cpp index 6264ff513..507fc9545 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -149,7 +149,7 @@ physics::Vehicle::Vehicle(double VelInitial, std::string const &TypeNameInit, st } Vel = abs(VelInitial); - V = VelInitial / 3.6; + travelSpeed = VelInitial / 3.6; RunningShape.Len = 1.0; @@ -182,7 +182,7 @@ void physics::Vehicle::change_train_velocity(double const Change) continue; } auto const otherdirection{direction * DirPatch(end, coupler.ConnectedEnd())}; - other->V += Change * otherdirection; + other->travelSpeed += Change * otherdirection; train.emplace_back(other, otherdirection); } } @@ -217,56 +217,56 @@ double physics::Vehicle::ComputeMovement(double dt, double dt1, const TTrackShap } if (CategoryFlag == 4) - OffsetTrackV = TotalMass / (Dim.L * Dim.W * 1000.0); + offsetTrackV = TotalMass / (Dim.L * Dim.W * 1000.0); else if (TestFlag(CategoryFlag, 1) && TestFlag(RunningTrack.CategoryFlag, 1) && DamageFlag.HasAll(VehicleDamage::derailed)) { - OffsetTrackV = -0.2; - OffsetTrackH = Sign(RunningShape.R) * 0.2; + offsetTrackV = -0.2; + offsetTrackH = Sign(RunningShape.R) * 0.2; } // TODO: investigate, seems supplied NewRot is always 0 although the code here suggests some actual values are expected - Loc = NewLoc; + location = NewLoc; Rot = NewRot; if (dL == 0) // oblicz przesuniecie} { - auto const AccSprev{AccS}; + auto const AccSprev{accS}; // przyspieszenie styczne - AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); + accS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one // derailed the legacy way with physics.collisions new if (DamageFlag.HasAll(VehicleDamage::derailed) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) - AccS = -Sign(V) * g * 1; // random(0.0, 0.1) + accS = -Sign(travelSpeed) * 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)}; + auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && travelSpeed == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; if (stuck) - AccS = 0.0; + accS = 0.0; // przyspieszenie normalne if (abs(Shape.R) > 0.01) - AccN = square(V) / Shape.R + g * Shape.dHrail / TrackW; // Q: zamieniam SQR() na sqr() + accN = square(travelSpeed) / Shape.R + g * Shape.dHrail / TrackW; // Q: zamieniam SQR() na sqr() else - AccN = g * Shape.dHrail / TrackW; + accN = g * Shape.dHrail / TrackW; // velocity change - auto const Vprev{V}; - V += (3.0 * AccS - AccSprev) * dt / 2.0; // przyrost predkosci + auto const Vprev{travelSpeed}; + travelSpeed += (3.0 * accS - AccSprev) * dt / 2.0; // przyrost predkosci if (stuck) - V = 0.0; - if (V * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) + travelSpeed = 0.0; + if (travelSpeed * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) { // tlumienie predkosci przy hamowaniu // zahamowany - V = 0; + travelSpeed = 0; } // tangential acceleration, from velocity change - AccSVBased = std::lerp(AccSVBased, (V - Vprev) / dt, std::clamp(dt * 3.0, 0.0, 1.0)); + AccSVBased = std::lerp(AccSVBased, (travelSpeed - Vprev) / dt, std::clamp(dt * 3.0, 0.0, 1.0)); // vertical acceleration - AccVert = std::abs(AccVert) < 0.01 ? 0.0 : AccVert * 0.5; + accVert = std::abs(accVert) < 0.01 ? 0.0 : accVert * 0.5; // szarpanie /* #ifdef EU07_USE_FUZZYLOGIC @@ -279,7 +279,7 @@ double physics::Vehicle::ComputeMovement(double dt, double dt1, const TTrackShap AccV = AccV / 2.0; if (AccV > 1.0) - AccN += (7.0 - Random(5)) * (100.0 + Track.DamageFlag / 2.0) * AccV / 2000.0; + accN += (7.0 - Random(5)) * (100.0 + Track.DamageFlag / 2.0) * AccV / 2000.0; */ // wykolejanie na luku oraz z braku szyn if (TestFlag(CategoryFlag, 1)) @@ -288,7 +288,7 @@ double physics::Vehicle::ComputeMovement(double dt, double dt1, const TTrackShap Derail(END_OF_TRACK); // too fast in a curve: the legacy draw in every step (physics.derailment old), or the physical criteria // once the step's distance is known, below - if ((Global.derailment == global_settings::derailment_model::old || Global.derailment == global_settings::derailment_model::monitor) && FuzzyLogic(AccN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) + if ((Global.derailment == global_settings::derailment_model::old || Global.derailment == global_settings::derailment_model::monitor) && FuzzyLogic(accN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) Derail(TOO_HIGH_SPEED); // wykolejanie na poszerzeniu toru if (FuzzyLogic(abs(Track.Width - TrackW), TrackW / 10.0, 1)) @@ -300,13 +300,13 @@ double physics::Vehicle::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} + dL = (3.0 * travelSpeed - 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)); + check_derailment(Shape, Track, derailmentDistance + std::abs(dL)); } - derailment_distance = 0.0; + derailmentDistance = 0.0; // ale jesli jest kolizja (zas. zach. pedu) to...} for (auto const b : VehicleEnds) if (Couplers[b].CheckCollision) @@ -318,7 +318,7 @@ double physics::Vehicle::ComputeMovement(double dt, double dt1, const TTrackShap auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu dL)}; - DistCounter += fabs(dL) / 1000.0; + distCounter += fabs(dL) / 1000.0; Odometer.run(dL); dL = 0; @@ -339,52 +339,52 @@ double physics::Vehicle::FastComputeMovement(double dt, const TTrackShape & /*Sh { // physics::Vehicle::FastComputeMovement(dt, Shape, Track, NewLoc, NewRot); - Loc = NewLoc; + location = NewLoc; Rot = NewRot; if (dL == 0) // oblicz przesuniecie { - auto const AccSprev{AccS}; + auto const AccSprev{accS}; // przyspieszenie styczne - AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); + 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 (DamageFlag.HasAll(VehicleDamage::derailed) && 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)}; + accS = -Sign(travelSpeed) * g * 1; // * random(0.0, 0.1) + auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && travelSpeed == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; if (stuck) - AccS = 0.0; + 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 + auto const Vprev{travelSpeed}; + travelSpeed += (3.0 * accS - AccSprev) * dt / 2.0; // przyrost predkosci if (stuck) - V = 0.0; - if (V * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) + travelSpeed = 0.0; + if (travelSpeed * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) { // tlumienie predkosci przy hamowaniu // zahamowany - V = 0; + travelSpeed = 0; } // simple mode skips calculation of tangential acceleration // simple mode skips calculation of vertical acceleration - AccVert = 0.0; + accVert = 0.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 == DamageFlag.HasAll(VehicleDamage::derailed) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this) && Vel < 1.0) { - V = 0.0; - AccS = 0.0; + travelSpeed = 0.0; + accS = 0.0; } - dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha + dL = (3.0 * travelSpeed - 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); + derailmentDistance += std::abs(dL); // ale jesli jest kolizja (zas. zach. pedu) to... for (auto const b : VehicleEnds) if (Couplers[b].CheckCollision) @@ -395,7 +395,7 @@ double physics::Vehicle::FastComputeMovement(double dt, const TTrackShape & /*Sh auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu dL)}; - DistCounter += fabs(dL) / 1000.0; + distCounter += fabs(dL) / 1000.0; Odometer.run(dL); dL = 0; @@ -534,7 +534,7 @@ bool physics::Vehicle::AddPulseForce(int Multipler) DirActive = CabActive; DirAbsolute = DirActive * CabActive; if (Vel > 0) - PulseForce = std::min(1000.0 * Power / (abs(V) + 0.1), Ftmax); + PulseForce = std::min(1000.0 * Power / (abs(travelSpeed) + 0.1), Ftmax); else PulseForce = Ftmax; if (PulseForceCount > 1000.0) @@ -707,13 +707,13 @@ void physics::Vehicle::ComputeConstans(void) // if (Ft * Ft < 1) // HideModifier = HideModifier - 3; } - Ff = TotalMassxg * (BearingF + RollF * V * V / 10.0) / 1000.0; + Ff = TotalMassxg * (BearingF + RollF * travelSpeed * travelSpeed / 10.0) / 1000.0; // dorobic liczenie temperatury lozyska! FrictConst1 = TotalMassxg * RollF / 10000.0; // drag calculation { // NOTE: draft effect of previous vehicle is simplified and doesn't have much to do with reality - auto const *previousvehicle{Couplers[V >= 0.0 ? VehicleEnd::front : VehicleEnd::rear].Connected}; + auto const *previousvehicle{Couplers[travelSpeed >= 0.0 ? VehicleEnd::front : VehicleEnd::rear].Connected}; auto dragarea{Dim.W * Dim.H}; if (previousvehicle) { @@ -776,7 +776,7 @@ void physics::Vehicle::ComputeMass() void physics::Vehicle::ComputeTotalForce(double dt) { - Vel = std::abs(V) * 3.6; // prędkość w km/h + Vel = std::abs(travelSpeed) * 3.6; // prędkość w km/h // McZapkie-031103: sprawdzanie czy warto liczyc fizyke i inne updaty // ABu 300105: cos tu mieszalem , dziala teraz troche lepiej, wiec zostawiam @@ -855,51 +855,51 @@ void physics::Vehicle::ComputeTotalForce(double dt) Fb = BrakeForce(RunningTrack); // poslizg - auto Fwheels{FTrain - Fb * Sign(V)}; + auto Fwheels{FTrain - Fb * Sign(travelSpeed)}; if (Vel > 0.1 // crude trap, to prevent braked stationary vehicles from passing fb > mass * adhesive test && std::abs(Fwheels) > TotalMassxg * Adhesive(RunningTrack.friction)) { SlippingWheels = true; } if (true == SlippingWheels && Vel < 0.1 // the same crude trap: (nearly) stopped vehicle... - && std::abs(nrot * M_PI * WheelDiameter - V) < 0.1 / 3.6) // ...with wheels turning at its speed, i.e. locked wheels at the end of a skid + && std::abs(nrot * M_PI * WheelDiameter - travelSpeed) < 0.1 / 3.6) // ...with wheels turning at its speed, i.e. locked wheels at the end of a skid { // locked wheels never pass the rotation speed test below once the vehicle stops, and a skidding vehicle // keeps its braking force capped by the sliding adhesion, so the rest of the consist could push it around SlippingWheels = false; - nrot = V / M_PI / WheelDiameter; + nrot = travelSpeed / M_PI / WheelDiameter; } double temp_nrot = nrot; if (true == SlippingWheels) { - temp_nrot = ComputeRotatingWheel(Fwheels - Sign(nrot * M_PI * WheelDiameter - V) * Adhesive(RunningTrack.friction) * TotalMassxg, dt, nrot); - if (Sign(nrot * M_PI * WheelDiameter - V) * Sign(temp_nrot * M_PI * WheelDiameter - V) < 0) + temp_nrot = ComputeRotatingWheel(Fwheels - Sign(nrot * M_PI * WheelDiameter - travelSpeed) * Adhesive(RunningTrack.friction) * TotalMassxg, dt, nrot); + if (Sign(nrot * M_PI * WheelDiameter - travelSpeed) * Sign(temp_nrot * M_PI * WheelDiameter - travelSpeed) < 0) { SlippingWheels = false; - temp_nrot = V / M_PI / WheelDiameter; + temp_nrot = travelSpeed / M_PI / WheelDiameter; } } if (true == SlippingWheels) { - Fwheels = Sign(temp_nrot * M_PI * WheelDiameter - V) * TotalMassxg * Adhesive(RunningTrack.friction); - if (Fwheels * Sign(V) > 0) + Fwheels = Sign(temp_nrot * M_PI * WheelDiameter - travelSpeed) * TotalMassxg * Adhesive(RunningTrack.friction); + if (Fwheels * Sign(travelSpeed) > 0) { - FTrain = Fwheels + Fb * Sign(V); + FTrain = Fwheels + Fb * Sign(travelSpeed); } - else if (FTrain * Sign(V) > 0) + else if (FTrain * Sign(travelSpeed) > 0) { - Fb = FTrain * Sign(V) - Fwheels * Sign(V); + Fb = FTrain * Sign(travelSpeed) - Fwheels * Sign(travelSpeed); } else { - double factor = FTrain - Fb * Sign(V) != 0 ? Fwheels / (FTrain - Fb * Sign(V)) : 1.0; + double factor = FTrain - Fb * Sign(travelSpeed) != 0 ? Fwheels / (FTrain - Fb * Sign(travelSpeed)) : 1.0; Fb *= factor; FTrain *= factor; } if (std::abs(nrot) < 0.1) { - WheelFlat = sqrt(square(WheelFlat) + abs(Fwheels) / NAxles * Vel * 0.000002); + wheelFlat = sqrt(square(wheelFlat) + abs(Fwheels) / NAxles * Vel * 0.000002); } nrot = temp_nrot; @@ -935,7 +935,7 @@ void physics::Vehicle::ComputeTotalForce(double dt) FTrain /= FT_factor; FTrain += TotalMassxg * RunningShape.dHtrack; //! niejawne przypisanie zmiennej! - FTotal = FTrain - Sign(V) * FStand; + FTotal = FTrain - Sign(travelSpeed) * FStand; } double physics::Vehicle::BrakeForceR(double ratio, double velocity) const @@ -1058,10 +1058,10 @@ double physics::Vehicle::FrictionForce() const { double FF = 0; // ABu 240205: chyba juz ekstremalnie zoptymalizowana funkcja liczaca sily tarcia - if (abs(V) > 0.01) - FF = FrictConst1 * V * V + FrictConst2d; + if (abs(travelSpeed) > 0.01) + FF = FrictConst1 * travelSpeed * travelSpeed + FrictConst2d; else - FF = FrictConst1 * V * V + FrictConst2s; + FF = FrictConst1 * travelSpeed * travelSpeed + FrictConst2s; return FF; } @@ -1112,7 +1112,7 @@ double physics::Vehicle::Adhesive(double staticfriction) const */ // wersja3 by youBy - uwzględnia naturalne mikropoślizgi i wpływ piasecznicy, usuwa losowość z pojazdu double Vwheels = nrot * M_PI * WheelDiameter; // predkosc liniowa koła wynikająca z obrotowej - double deltaV = V - Vwheels; // poślizg - różnica prędkości w punkcie styku koła i szyny + double deltaV = travelSpeed - Vwheels; // poślizg - różnica prędkości w punkcie styku koła i szyny deltaV = std::max(0.0, std::abs(deltaV) - 0.25); // mikropoślizgi do ok. 0,25 m/s nie zrywają przyczepności Vwheels = std::abs(Vwheels); adhesion = staticfriction * (28 + Vwheels) / (14 + Vwheels) * ((SandDose ? sandfactor : 1) - (1 - adh_factor) * (deltaV / (deltaV + slipfactor))); @@ -1128,7 +1128,7 @@ double physics::Vehicle::ComputeRotatingWheel(double WForce, double dt, double n { double newn = 0; double eps = 0; - if (n == 0 && WForce * Sign(V) < 0) + if (n == 0 && WForce * Sign(travelSpeed) < 0) newn = 0; else { @@ -1149,9 +1149,9 @@ bool physics::Vehicle::ChangeOffsetH(double DeltaOffset) bool COH = false; if (TestFlag(CategoryFlag, 2) && TestFlag(RunningTrack.CategoryFlag, 2)) { - OffsetTrackH = OffsetTrackH + DeltaOffset; + offsetTrackH = offsetTrackH + DeltaOffset; // if (abs(OffsetTrackH) > (RunningTrack.Width / 1.95 - TrackW / 2.0)) - if (abs(OffsetTrackH) > 0.5 * (RunningTrack.Width - Dim.W) - 0.05) // Ra: może pół pojazdu od brzegu? + if (abs(offsetTrackH) > 0.5 * (RunningTrack.Width - Dim.W) - 0.05) // Ra: może pół pojazdu od brzegu? COH = false; // kola na granicy drogi else COH = true; @@ -1184,7 +1184,7 @@ std::string physics::Vehicle::EngineDescription(int what) const else outstr = "Load shifted"; } - if (WheelFlat > 5.0 || DamageFlag.HasAll(VehicleDamage::wheelWear)) + if (wheelFlat > 5.0 || DamageFlag.HasAll(VehicleDamage::wheelWear)) { outstr = "Wheel wear"; } @@ -1232,7 +1232,7 @@ std::string physics::Vehicle::EngineDescription(int what) const // ************************************************************************************************* bool physics::Vehicle::accelerating() const { - if (std::abs(AccS) <= 0.0001) + if (std::abs(accS) <= 0.0001) return false; // standing still and held by the brakes and the resistance, against the slope and the couplers: the test ComputeMovement() // sets the speed to zero by. the forces are of the last ComputeTotalForce(), the ones the movement went by. a vehicle whose diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index 2540af46f..1b421558b 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -58,7 +58,7 @@ bool physics::Vehicle::ChangeCab(int direction) { BrakeLevelSet(brakes.driverValve->GetPos(bh_NP)); brakes.pipeLimiterPressure = brakePipe.Pressure(); - ActFlowSpeed = 0; + actFlowSpeed = 0; } else BrakeLevelSet(brakes.driverValve->GetPos(bh_NP)); @@ -150,7 +150,7 @@ bool physics::Vehicle::CabDeactivisation(bool const Enforce) } if (InactiveCabFlag & activation::pantographsup) { - InactiveCabPantsCheck = true; + inactiveCabPantsCheck = true; } if (InactiveCabFlag & activation::doorpermition) { diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index b78a9010f..4d62b829e 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -106,8 +106,8 @@ void physics::Vehicle::CollisionDetect(VehicleEnd const End, double const dt) // the velocities along this vehicle's axis: the other vehicle's one is turned around when the vehicles face each // other (touch with the same ends), as in CouplerForce() auto const otherdirection{DirPatch(End, otherend)}; - auto velocity{V}; - auto othervehiclevelocity{othervehicle->V * otherdirection}; + auto velocity{travelSpeed}; + auto othervehiclevelocity{othervehicle->travelSpeed * otherdirection}; // calculate collision force and new velocities for involved vehicles auto const VirtualCoupling{(thiscoupler.CouplingFlag == Coupling::none)}; auto CCF{0.0}; @@ -175,16 +175,16 @@ void physics::Vehicle::CollisionDetect(VehicleEnd const End, double const dt) }; if (false == wall(*this)) { - auto const accelerationchange{(velocity - V) / dt}; - AccS += accelerationchange * accelerationspike; - V = velocity; + auto const accelerationchange{(velocity - travelSpeed) / dt}; + accS += accelerationchange * accelerationspike; + travelSpeed = velocity; } if (false == wall(*othervehicle)) { auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis - auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->V) / dt}; - othervehicle->AccS += othervehicleaccelerationchange * accelerationspike; - othervehicle->V = othervehiclenewvelocity; + auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->travelSpeed) / dt}; + othervehicle->accS += othervehicleaccelerationchange * accelerationspike; + othervehicle->travelSpeed = othervehiclenewvelocity; } } @@ -462,11 +462,11 @@ bool physics::Vehicle::crush_hit(VehicleEnd const End, double const dt) auto const apart{End == VehicleEnd::front ? -1.0 : 1.0}; if (false == wall) { - V += apart * hit.impulse / mass; + travelSpeed += apart * hit.impulse / mass; } if (false == otherwall) { - othervehicle->V -= apart * hit.impulse / othermass * otherdirection; + othervehicle->travelSpeed -= apart * hit.impulse / othermass * otherdirection; } record_hit(thiscoupler, hit.force, hit.duration); record_hit(othercoupler, hit.force, hit.duration); @@ -708,7 +708,7 @@ void physics::Vehicle::check_derailment(TTrackShape const &Shape, TTrackParam co track.buckle_curvature = Shape.buckle_curvature; track.damage = Track.DamageFlag; - auto const verdict{derailment_monitor.update(vehicle, track, V, Distance)}; + auto const verdict{derailment_monitor.update(vehicle, track, travelSpeed, Distance)}; if (verdict.result == derailment::outcome::none) { return; @@ -725,7 +725,7 @@ void physics::Vehicle::check_derailment(TTrackShape const &Shape, TTrackParam co } derailment_reported = Track.Name; ++derailment_reports; - WriteLog("derailment monitor: " + Name + " " + derailment::report(verdict, vehicle, track, V, Track.Name != nullptr ? *Track.Name : std::string{})); + WriteLog("derailment monitor: " + Name + " " + derailment::report(verdict, vehicle, track, travelSpeed, Track.Name != nullptr ? *Track.Name : std::string{})); } void physics::Vehicle::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName) @@ -743,7 +743,7 @@ void physics::Vehicle::derail(derailment::verdict const &Verdict, derailment::ve 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{})); + ErrorLog("Bad driving: " + Name + " " + derailment::report(Verdict, Vehicle, Track, travelSpeed, 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), @@ -761,7 +761,7 @@ void physics::Vehicle::rerail() DerailAcceleration = 0.0; DerailSide = 0; derailment_monitor.reset(); - derailment_distance = 0.0; + derailmentDistance = 0.0; derailment_reported.reset(); // nor derailed in a collision CollisionDerail = NONE; @@ -770,8 +770,8 @@ void physics::Vehicle::rerail() // its place on the road) if (TestFlag(CategoryFlag, 1)) { - OffsetTrackH = 0.0; - OffsetTrackV = 0.0; + offsetTrackH = 0.0; + offsetTrackV = 0.0; } // a derailed vehicle which stopped sleeps (Global.physics_sleepheld) with the friction of the derailment in FStand and // where the derailment put it, until something wakes it: the physics on, for the friction of the rails and its place on @@ -783,7 +783,7 @@ void physics::Vehicle::repair_damage() { DamageFlag = {}; equipmentFaults = {}; - WheelFlat = 0.0; + wheelFlat = 0.0; brakes.alarmChain = false; // the crushed ends rebuilt for (auto &coupler : Couplers) @@ -800,15 +800,15 @@ void physics::Vehicle::Derail(DerailReason const Reason) eventFlag = true; MainSwitch(false, range_t::local); - auto const velocity{V}; - AccS *= 0.65; - V *= 0.65; + auto const velocity{travelSpeed}; + accS *= 0.65; + travelSpeed *= 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); + change_train_velocity(travelSpeed - velocity); } RunningShape.R = 0; if (Vel < 5.0) diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index f8e9130a3..50e26c96d 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -734,7 +734,7 @@ bool physics::Vehicle::RunLoadCommand(VehicleCommand const Command, double CValu { OK = false; // będzie powtarzane aż się załaduje if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist - && maxLoad > 0 && loadAmount < maxLoad * (1.0 + OverLoadFactor) && Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) + && maxLoad > 0 && loadAmount < maxLoad * (1.0 + OverLoadFactor) && Distance(location, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) { // ten peron/rampa auto const loadname{ToLower(std::string{Argument})}; @@ -756,7 +756,7 @@ bool physics::Vehicle::RunLoadCommand(VehicleCommand const Command, double CValu OK = false; // będzie powtarzane aż się rozładuje if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist && loadAmount > 0 // czy jest co rozladowac? - && Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) + && Distance(location, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) { // ten peron /*mozna to rozladowac*/ OK = LoadingDone(-1.f * LoadSpeed, ToLower(std::string{Argument})); diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index 17e34428e..e54a8beb5 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -1036,7 +1036,7 @@ void physics::Vehicle::CheckEIMIC(double dt) // the controller (EIMCtrlType 0): the position of the main controller, or the analog one, or the brake asked void physics::Vehicle::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; + eimic = brakeDemand > 0.01 ? -brakeDemand : eimicAnalog > 0.01 ? eimicAnalog : (double)mainCtrlPos / (double)MainCtrlPosNo; if (EIMCtrlAdditionalZeros || EIMCtrlEmergency) { if (eimic > 0.001) diff --git a/physics/components/couplers.cpp b/physics/components/couplers.cpp index 6de010fff..dd0e300e6 100644 --- a/physics/components/couplers.cpp +++ b/physics/components/couplers.cpp @@ -42,7 +42,7 @@ double physics::Vehicle::Distance(const TLocation &Loc1, const TLocation &Loc2, double physics::Vehicle::CouplerDist(physics::Vehicle const *Left, physics::Vehicle const *Right) { // obliczenie odległości pomiędzy sprzęgami (kula!) - return Distance(Left->Loc, Right->Loc, Left->Dim, Right->Dim); // odległość pomiędzy sprzęgami (kula!) + return Distance(Left->location, Right->location, Left->Dim, Right->Dim); // odległość pomiędzy sprzęgami (kula!) }; bool physics::Vehicle::Attach(int ConnectNo, int ConnectToNr, physics::Vehicle *ConnectTo, CouplingSet CouplingType, bool Enforce, bool Audible) @@ -194,7 +194,7 @@ double physics::Vehicle::CouplerVelocityDifference(VehicleEnd const End, physics { // V runs along the vehicle's own axis, towards its front; the other vehicle's velocity is turned around when the // vehicles face each other (touch with the same ends) - return V - Other.V * DirPatch(End, OtherEnd); + return travelSpeed - Other.travelSpeed * DirPatch(End, OtherEnd); } bool physics::Vehicle::AutomaticCouplingSafe(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const @@ -271,9 +271,9 @@ double physics::Vehicle::CouplerForce(VehicleEnd const End, double dt) auto const otherend{Neighbours[End].FacingEnd()}; auto const &othercoupler{othervehicle->Couplers[otherend]}; - auto const othervehiclemove{(othervehicle->dMoveLen * DirPatch(End, otherend))}; + auto const othervehiclemove{(othervehicle->moveLength * DirPatch(End, otherend))}; auto const initialdistance{Neighbours[End].distance}; // odległość od sprzęgu sąsiada - auto const distancedelta{(End == VehicleEnd::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; + auto const distancedelta{(End == VehicleEnd::front ? othervehiclemove - moveLength : moveLength - othervehiclemove)}; // 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}; @@ -411,13 +411,13 @@ bool physics::Vehicle::coupler_physics_at(VehicleEnd const End) const { return false; } - if (Global.coupler_physics_all || CouplerPhysics) + if (Global.coupler_physics_all || couplerPhysics) { return true; } // either vehicle of the pair covered takes the pair in, so both of them compute it the same way auto const *other{Neighbours[End].vehicle}; - return other != nullptr && other->physics->CouplerPhysics; + return other != nullptr && other->physics->couplerPhysics; } void physics::Vehicle::automatic_coupling(VehicleEnd const End, physics::Vehicle &Other, VehicleEnd const OtherEnd) @@ -499,8 +499,8 @@ double physics::Vehicle::coupler_force_physical(VehicleEnd const End, double con auto &state{thiscoupler.physics_state}; // the gap as it is now: the distance found at the start of the frame, and the movement of both vehicles since - auto const othervehiclemove{othervehicle->dMoveLen * DirPatch(End, otherend)}; - auto const gap{Neighbours[End].distance + (End == VehicleEnd::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; + auto const othervehiclemove{othervehicle->moveLength * DirPatch(End, otherend)}; + auto const gap{Neighbours[End].distance + (End == VehicleEnd::front ? othervehiclemove - moveLength : moveLength - othervehiclemove)}; // the gap opens up when the front end falls behind the vehicle ahead of it, or the rear end runs ahead of the one behind auto const gaprate{CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; auto const coupled{thiscoupler.CouplingFlag != Coupling::none}; diff --git a/physics/components/diesel.cpp b/physics/components/diesel.cpp index b6c781690..4ebbc65bd 100644 --- a/physics/components/diesel.cpp +++ b/physics/components/diesel.cpp @@ -586,9 +586,9 @@ double physics::Vehicle::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) + if (brake.max_power > 0.0 && std::abs(travelSpeed) > 0.0) { - limit = std::min(limit, brake.max_power / std::abs(V)); + limit = std::min(limit, brake.max_power / std::abs(travelSpeed)); } if (brake.fade_high > brake.fade_low) { @@ -632,8 +632,8 @@ void physics::Vehicle::update_dieselelectric_dynamic_brake(double const dt) // would turn round each time the speed crosses zero, and in FTrain it never lets the stop of ComputeMovement() catch it void physics::Vehicle::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; + auto const force{dt > 0.0 ? std::min(DEDynamicBrake.force, TotalMass * std::abs(travelSpeed) / dt) : DEDynamicBrake.force}; + Ft = travelSpeed > 0.0 ? -force : travelSpeed < 0.0 ? force : 0.0; Fw = Ft / NPoweredAxles; Mw = Fw * WheelDiameter / 2.0; Mm = Mw / Transmision.Ratio; diff --git a/physics/components/securitysystem.cpp b/physics/components/securitysystem.cpp index 051413cdf..d922c51f2 100644 --- a/physics/components/securitysystem.cpp +++ b/physics/components/securitysystem.cpp @@ -276,7 +276,7 @@ bool physics::Vehicle::RadiostopSwitch(bool Switch) } else { - if (Switch == false && std::abs(V) < 0.1) + if (Switch == false && std::abs(travelSpeed) < 0.1) { // odblokowanie hamulca bezpieczenistwa tylko po zatrzymaniu radioStopFlag = Switch; diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index 36b415f3c..e2af68095 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -127,7 +127,7 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) SetBraked(); } - ActFlowSpeed = 0.0; + actFlowSpeed = 0.0; brakes.SetHandlePositionReal(brakes.HandlePosition()); if (brakes.config.independentValveType == TBrakeHandle::Knorr) diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index aedc46797..6767bac9c 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -672,7 +672,7 @@ void physics::Vehicle::DumbTractionForce(double const PosRatio) { if (Vel > 0.1) { - Ft = std::min(1000.0 * Power / std::abs(V), Ftmax) * PosRatio; + Ft = std::min(1000.0 * Power / std::abs(travelSpeed), Ftmax) * PosRatio; } else { @@ -1197,9 +1197,9 @@ double physics::Vehicle::InductionMotorBrakeRatio(double const ActiveInverters, { double PosRatio; // ustalanie współczynnika blendingu do luzowania hamulca PN - if (inductionMotor.state.maxForce * Sign(V) * DirAbsolute < -1) + if (inductionMotor.state.maxForce * Sign(travelSpeed) * DirAbsolute < -1) { - PosRatio = -Sign(V) * DirAbsolute * inductionMotor.state.force / (inductionMotor.braking.maxForce * std::max(edBCP, std::max(0.01, brakes.distributor->GetEDBCP())) / brakes.config.maxCylinderPressure[0]); + PosRatio = -Sign(travelSpeed) * DirAbsolute * inductionMotor.state.force / (inductionMotor.braking.maxForce * std::max(edBCP, std::max(0.01, brakes.distributor->GetEDBCP())) / brakes.config.maxCylinderPressure[0]); PosRatio = std::clamp(PosRatio, 0.0, 1.0); } else @@ -1320,11 +1320,11 @@ void physics::Vehicle::InductionMotorForceLimits() if (inductionMotor.forceShare < 0) { inductionMotor.state.fullForce = std::min(inductionMotor.braking.maxPower * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(inductionMotor.braking.maxForce, inductionMotor.state.absoluteMaxForce)); - inductionMotor.state.maxForce = -Sign(V) * DirAbsolute*std::min(inductionMotor.braking.maxPower * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-inductionMotor.braking.maxForce * inductionMotor.forceShare, inductionMotor.state.absoluteMaxForce)); + inductionMotor.state.maxForce = -Sign(travelSpeed) * DirAbsolute*std::min(inductionMotor.braking.maxPower * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-inductionMotor.braking.maxForce * inductionMotor.forceShare, inductionMotor.state.absoluteMaxForce)); double pr = inductionMotor.forceShare; if (inductionMotor.logForce) pr = -log(1 - 4 * pr) / log(5); - inductionMotor.state.force = -Sign(V) * DirAbsolute*std::min(inductionMotor.braking.maxPower * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-inductionMotor.braking.maxForce * pr, inductionMotor.state.absoluteMaxForce)); + inductionMotor.state.force = -Sign(travelSpeed) * DirAbsolute*std::min(inductionMotor.braking.maxPower * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-inductionMotor.braking.maxForce * pr, inductionMotor.state.absoluteMaxForce)); if (inductionMotor.inverterRatio < 1.0) inductionMotor.state.fullForce = 0; //*std::min(1,(Vel-inductionMotor.braking.offSpeed)/(inductionMotor.braking.fullSpeed-inductionMotor.braking.offSpeed)) @@ -1512,7 +1512,7 @@ double physics::Vehicle::v2n(void) double n; double deltan = 0; - n = V / (M_PI * WheelDiameter); // predkosc obrotowa wynikajaca z liniowej [obr/s] + n = travelSpeed / (M_PI * WheelDiameter); // predkosc obrotowa wynikajaca z liniowej [obr/s] deltan = n - nrot; //"pochodna" prędkości obrotowej /* if (SlippingWheels) if (std::abs(deltan) < 0.001) diff --git a/physics/consistbraking.cpp b/physics/consistbraking.cpp index 235e9ac0c..423b636e4 100644 --- a/physics/consistbraking.cpp +++ b/physics/consistbraking.cpp @@ -183,7 +183,7 @@ void physics::ConsistBrakeBlending::ComputeDemand(Step &state, Vehicle &Lead, do // the holding brake lets go once power has been demanded for its delay (SBDReleaseDelay, none by default) auto const holdingbrakereleased { Lead.UpdateStopBrakeRelease( state.eimic, dt1 ) }; if (Lead.ShuntMode && false == holdingbrakereleased || state.doorisopen /*|| - (Lead.V * Lead.DirAbsolute < -0.2)*/) + (Lead.V() * Lead.DirAbsolute < -0.2)*/) { auto const sbd { ( Lead.brakes.spring.isActive && Lead.brakes.spring.releasesParking ? 0.0 : Lead.brakes.holding.deceleration ) }; state.Fzad = std::max( state.Fzad, sbd * state.masa ); diff --git a/physics/vehicle.h b/physics/vehicle.h index 8c836d3db..bf1f66bcb 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -622,7 +622,8 @@ class Vehicle public: std::string chkPath; bool reload_FIZ(); - double dMoveLen = 0.0; + double const &MoveLength() const { return moveLength; } + void SetMoveLength(double const Value) { moveLength = Value; } /*---opis lokomotywy, wagonu itp*/ /*--opis serii--*/ int CategoryFlag = 1; /*1 - pociag, 2 - samochod, 4 - statek, 8 - samolot*/ @@ -897,14 +898,16 @@ class Vehicle double SpeedCtrlValue = 0; /*wybrana predkosc jazdy na tempomacie*/ /*--sekcja zmiennych*/ /*--opis konkretnego egzemplarza taboru*/ - TLocation Loc{0.0, 0.0, 0.0}; // pozycja pojazdów do wyznaczenia odległości pomiędzy sprzęgami + TLocation const &Loc() const { return location; } // pozycja pojazdów do wyznaczenia odległości pomiędzy sprzęgami + void SetLoc(TLocation const Value) { location = Value; } TRotation Rot{0.0, 0.0, 0.0}; glm::vec3 Front{}; std::string Name; /*nazwa wlasna*/ ByEnd Couplers; // urzadzenia zderzno-sprzegowe, polaczenia miedzy wagonami // the physical coupler model covers the vehicle: it's in the player's train or in one the player's train closes in on // (vehicle_table::update_coupler_physics()); with couplerphysics all in eu07.ini every vehicle is covered - bool CouplerPhysics{false}; + bool const &CouplerPhysics() const { return couplerPhysics; } + void SetCouplerPhysics(bool const Value) { couplerPhysics = Value; } ByEnd Neighbours; // potential collision sources // something out of the ordinary happened (the line breaker knocked out, a derailment), for the sounds to follow up bool EventFlag() const { return eventFlag; } @@ -914,26 +917,41 @@ class Vehicle int SoundFlag() const { return soundFlag; } void ClearSoundFlags() { soundFlag = 0; } int AIFlag{0}; // HACK: events of interest for consist owner - double DistCounter = 0.0; /*! licznik kilometrow */ + double const &DistCounter() const { return distCounter; } /*! licznik kilometrow */ + void SetDistCounter(double const Value) { distCounter = Value; } // 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; + double const &DerailmentDistance() const { return derailmentDistance; } + void SetDerailmentDistance(double const Value) { derailmentDistance = Value; } // 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) + double const &V() const { return travelSpeed; } // predkosc w [m/s] względem sprzęgów (dodania gdy jedzie w stronę 0) + void SetV(double const Value) { travelSpeed = Value; } double Vel = 0.0; // moduł prędkości w [km/h], używany przez AI - double AccS = 0.0; // efektywne przyspieszenie styczne w [m/s^2] (wszystkie siły) + double const &AccS() const { return accS; } // efektywne przyspieszenie styczne w [m/s^2] (wszystkie siły) + void SetAccS(double const Value) { accS = Value; } double AccSVBased{}; // tangential acceleration calculated from velocity change - double AccN = 0.0; // przyspieszenie normalne w [m/s^2] - double AccVert = 0.0; // vertical acceleration + double const &AccN() const { return accN; } // przyspieszenie normalne w [m/s^2] + void SetAccN(double const Value) { accN = Value; } + double const &AccVert() const { return accVert; } // vertical acceleration + void SetAccVert(double const Value) { accVert = Value; } + // a jolt of the track under the vehicle: up and down, or along and across (a switch) + void ShakeVertically(double const Acceleration) { accVert += Acceleration; } + void ShakeHorizontally(double const Acceleration) + { + accS += Acceleration; + accN += Acceleration; + } double nrot = 0.0; // predkosc obrotowa kol (obrotow na sekunde) double nrot_eps = 0.0; // przyspieszenie kątowe kół (bez kierunku) - double WheelFlat = 0.0; - bool TruckHunting{true}; // enable/disable truck hunting calculation + double const &WheelFlat() const { return wheelFlat; } + void SetWheelFlat(double const Value) { wheelFlat = Value; } + bool const &TruckHunting() const { return truckHunting; } // enable/disable truck hunting calculation + void SetTruckHunting(bool const Value) { truckHunting = Value; } /*! rotacja kol [obr/s]*/ double EnginePower = 0.0; /*! chwilowa moc silnikow*/ double dL = 0.0; @@ -973,7 +991,8 @@ class Vehicle bool TUHEX_ResChange = false; /*czy zmiana rezystancji hamowania ED - odwzbudzanie*/ bool TUHEX_Active = false; /*czy hamowanie ED wywołane z zewnątrz*/ // NapUdWsp: integer; - double ActFlowSpeed = 0.0; /*szybkosc stabilizatora*/ + double const &ActFlowSpeed() const { return actFlowSpeed; } /*szybkosc stabilizatora*/ + void SetActFlowSpeed(double const Value) { actFlowSpeed = Value; } DamageSet DamageFlag; // the damage of the vehicle EquipmentFaultSet equipmentFaults; // the faults of the equipment set on the vehicle (SetEquipmentFaults()) @@ -986,8 +1005,10 @@ class Vehicle TTrackShape RunningShape; /*geometria toru po ktorym jedzie pojazd*/ TTrackParam RunningTrack; /*parametry toru po ktorym jedzie pojazd*/ - double OffsetTrackH = 0.0; - double OffsetTrackV = 0.0; /*przesuniecie poz. i pion. w/m osi toru*/ + double const &OffsetTrackH() const { return offsetTrackH; } + void SetOffsetTrackH(double const Value) { offsetTrackH = Value; } + double const &OffsetTrackV() const { return offsetTrackV; } /*przesuniecie poz. i pion. w/m osi toru*/ + void SetOffsetTrackV(double const Value) { offsetTrackV = Value; } /*-zmienne dla lokomotyw*/ bool ReleaserEnabledOnlyAtNoPowerPos{false}; @@ -1013,12 +1034,14 @@ class Vehicle } // czy aktualna kabina jest na pewno tą, z której można sterować bool AutomaticCabActivation = true; // czy zmostkowany rozrzad przelacza sie sam przy zmianie kabiny int InactiveCabFlag = 0; // co sie dzieje przy dezaktywacji kabiny - bool InactiveCabPantsCheck = false; // niech DynamicObject sprawdzi pantografy + bool const &InactiveCabPantsCheck() const { return inactiveCabPantsCheck; } // niech DynamicObject sprawdzi pantografy + void SetInactiveCabPantsCheck(bool const Value) { inactiveCabPantsCheck = Value; } double LastSwitchingTime = 0.0; /*czas ostatniego przelaczania czegos*/ int const &WarningSignal() const { return warningSignal; } // 0: nie trabi, 1,2,4: trabi void SetWarningSignal(int const Value) { warningSignal = Value; } bool DepartureSignal = false; /*sygnal odjazdu*/ - bool InsideConsist = false; + bool const &InsideConsist() const { return insideConsist; } + void SetInsideConsist(bool const Value) { insideConsist = Value; } /*-zmienne dla lokomotywy elektrycznej*/ TTractionParam RunningTraction; /*parametry sieci trakcyjnej najblizej lokomotywy*/ double enrot = 0.0; // ilosc obrotow silnika @@ -1055,7 +1078,8 @@ class Vehicle /*- zmienne dla lokomotyw z silnikami indukcyjnymi -*/ double eimic = 0; /*aktualna pozycja zintegrowanego sterowania jazda i hamowaniem*/ - double eimic_analog = 0; /*pozycja zadajnika analogowa*/ + double const &EimicAnalog() const { return eimicAnalog; } /*pozycja zadajnika analogowa*/ + void SetEimicAnalog(double const Value) { eimicAnalog = Value; } double eimic_real = 0; /*faktycznie uzywana pozycja zintegrowanego sterowania jazda i hamowaniem*/ double eimic_step_progress{0.0}; // the part of the next UniCtrlValStep the controller has covered so far double eim_localbrake = 0; /*nastawa hamowania dodatkowego pneumatycznego lokomotywy*/ @@ -1817,6 +1841,23 @@ class Vehicle private: // the switches and the controllers the cab, the AI and the scenery change only through the operations above + double travelSpeed = 0.0; + TLocation location{0.0, 0.0, 0.0}; + double offsetTrackH = 0.0; + double offsetTrackV = 0.0; + double accS = 0.0; + double accN = 0.0; + double accVert = 0.0; + double distCounter = 0.0; + double moveLength = 0.0; + double wheelFlat = 0.0; + bool truckHunting{true}; + double derailmentDistance = 0.0; + bool insideConsist = false; + bool couplerPhysics{false}; + bool inactiveCabPantsCheck = false; + double eimicAnalog = 0; + double actFlowSpeed = 0.0; float maxLoad = 0.f; bool eventFlag = false; int soundFlag = 0; diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index d5ab1df1a..24db6b236 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -225,7 +225,7 @@ blackbox::vehicle_state state_of(TDynamicObject const &Vehicle, std::uint32_t co state.position = glm::vec3{Vehicle.GetPosition()}; auto const front{Vehicle.VectorFront()}; state.heading = static_cast(std::atan2(front.x, front.z)); - state.speed_kmh = static_cast(Vehicle.physics->V * 3.6); + state.speed_kmh = static_cast(Vehicle.physics->V() * 3.6); state.driving = driver_of(Vehicle); return state; } @@ -424,7 +424,7 @@ void blackbox_recorder::write_cab() { sample.time = m_time; sample.vehicle = vehicle_id(vehicle); sample.position = vehicle->GetPosition(); - sample.speed_kmh = static_cast(occupied->V * 3.6); + sample.speed_kmh = static_cast(occupied->V() * 3.6); // of the wheels as they turn, which the speedometer shows: apart from that of the vehicle when they slip or skid. // those of the powered vehicle, as the speedometer has it (TTrain::DynamicSet), which in a unit driven from an // unpowered car is another one, maybe facing the other way: signed as the occupied one's speed @@ -432,8 +432,8 @@ void blackbox_recorder::write_cab() { auto const *powered{train->Dynamic()->FindPowered()}; auto const facing{powered->DirectionGet() * vehicle->DirectionGet()}; sample.wheel_speed_kmh = static_cast(facing * M_PI * powered->physics->WheelDiameter * powered->physics->nrot * 3.6); - sample.acceleration = static_cast(controlling->AccS); - sample.lateral_acceleration = static_cast(occupied->AccN); + sample.acceleration = static_cast(controlling->AccS()); + sample.lateral_acceleration = static_cast(occupied->AccN()); if (owner != nullptr && owner->is_train()) { auto const order{owner->order_current()}; sample.movement = order.HasAny(DriverOrder::obeyTrain) ? blackbox::movements::train : @@ -441,7 +441,7 @@ void blackbox_recorder::write_cab() { sample.light_hint_head = static_cast(owner->light_hint(VehicleEnd::front)); sample.light_hint_tail = static_cast(owner->light_hint(VehicleEnd::rear)); } - sample.odometer_km = static_cast(occupied->DistCounter); + sample.odometer_km = static_cast(occupied->DistCounter()); sample.driving = driver_of(*vehicle); sample.flags = (FreeFlyModeFlag ? 0 : blackbox::cab_flags::in_cab) | (owner != nullptr && owner->is_active() ? blackbox::cab_flags::ai_valid : 0) | (controlling->SecuritySystem.is_blinking() ? blackbox::cab_flags::alerter_blinking : 0) | @@ -598,7 +598,7 @@ void blackbox_recorder::look_at_derailments() { 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->physics->V * 3.6); + state.speed_kmh = static_cast(vehicle->physics->V() * 3.6); state.offset = static_cast(vehicle->off_track_offset()); state.roll = static_cast(motion.roll()); state.travelled = static_cast(motion.travelled()); diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index e0ec57730..8c2e9f0d3 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -437,10 +437,10 @@ void state_manager::process_commands() { while (vehicle) { // no damage, back on the rails with the state of the derailment cleared vehicle->physics->repair_damage(); - vehicle->physics->V = 0.000001; // HACK: force vehicle position re-calculation - vehicle->physics->DistCounter = 0.0; - vehicle->physics->OffsetTrackH = 0.0; - vehicle->physics->OffsetTrackV = 0.0; + vehicle->physics->SetV(0.000001); // HACK: force vehicle position re-calculation + vehicle->physics->SetDistCounter(0.0); + vehicle->physics->SetOffsetTrackH(0.0); + vehicle->physics->SetOffsetTrackV(0.0); // pantographs for( auto idx = 0; idx < vehicle->iAnimType[ ANIM_PANTS ]; ++idx ) { diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index 5e82d4e88..796943c7d 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -19,14 +19,14 @@ vehicle &consist::add(definition const &Definition, int Cab, CouplingSet const c if (false == m_vehicles.empty()) { auto &last{m_vehicles.back()->physics()}; position = m_positions.back() - 0.5 * (last.Dim.L + physics.Dim.L) - Gap; - physics.Loc = TLocation{position, 0.0, 0.0}; + physics.SetLoc(TLocation{position, 0.0, 0.0}); if (false == couplings.Empty()) { last.Attach(VehicleEnd::rear, VehicleEnd::front, &physics, couplings, true, false); physics.Attach(VehicleEnd::front, VehicleEnd::rear, &last, couplings, true, false); } } else { - physics.Loc = TLocation{position, 0.0, 0.0}; + physics.SetLoc(TLocation{position, 0.0, 0.0}); } m_vehicles.push_back(std::move(added)); m_positions.push_back(position); @@ -51,7 +51,7 @@ void consist::update_neighbours() { auto const distance{physics::Vehicle::CouplerDist(&physics, &otherPhysics) - physics.Couplers[end].adapter_length - otherPhysics.Couplers[otherend].adapter_length}; // a vehicle not coupled is a collision source when it's within the range the game scans - if (physics.Couplers[end].Connected == nullptr && distance > std::max(10.0, std::abs(physics.V)) + 40.0) { + if (physics.Couplers[end].Connected == nullptr && distance > std::max(10.0, std::abs(physics.V())) + 40.0) { neighbour = neighbour_data(); continue; } diff --git a/tests/unit/figures.cpp b/tests/unit/figures.cpp index f3325c0a2..ce086154c 100644 --- a/tests/unit/figures.cpp +++ b/tests/unit/figures.cpp @@ -61,20 +61,20 @@ constexpr double pipe_back{4.9}; void figures::sample(double Time, physics::Vehicle const &Vehicle) { auto &part{m_parts.back()}; - auto const speed{Vehicle.V * 3.6}; + auto const speed{Vehicle.V() * 3.6}; auto const pipe{Vehicle.brakePipe.Pressure()}; if (false == part.sampled) { part.sampled = true; // from the last step of the part before, so the parts add up to the run part.start = m_last_time < 0.0 ? Time : m_last_time; part.speed_start = m_last_time < 0.0 ? speed : m_last_speed; - part.distance_start = m_last_time < 0.0 ? Vehicle.DistCounter : m_last_distance; + part.distance_start = m_last_time < 0.0 ? Vehicle.DistCounter() : m_last_distance; part.pipe_lowest = pipe; } part.end = Time; part.speed_end = speed; part.speed_peak = std::max(part.speed_peak, std::abs(speed)); - part.distance_end = Vehicle.DistCounter; + part.distance_end = Vehicle.DistCounter(); if (part.stopped < 0.0 && std::abs(part.speed_start) > 1.0 && std::abs(speed) < 0.05) { part.stopped = Time - part.start; } @@ -92,7 +92,7 @@ void figures::sample(double Time, physics::Vehicle const &Vehicle) { m_last_time = Time; m_last_speed = speed; - m_last_distance = Vehicle.DistCounter; + m_last_distance = Vehicle.DistCounter(); // which figures the vehicle has, over the whole run, so each part has the same ones m_moved |= std::abs(speed) >= 0.05; m_piped |= pipe >= 0.1; diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index da5f146c4..429349288 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -42,9 +42,9 @@ namespace channels { std::vector motion() { return { - {"V", [](auto const &M) { return M.V; }}, - {"DistCounter", [](auto const &M) { return M.DistCounter; }}, - {"AccS", [](auto const &M) { return M.AccS; }}, + {"V", [](auto const &M) { return M.V(); }}, + {"DistCounter", [](auto const &M) { return M.DistCounter(); }}, + {"AccS", [](auto const &M) { return M.AccS(); }}, {"nrot", [](auto const &M) { return M.nrot; }}, {"Ft", [](auto const &M) { return M.Ft; }}, {"Fb", [](auto const &M) { return M.Fb; }}, @@ -278,7 +278,7 @@ void trace::sample(double Time, physics::Vehicle const &Vehicle) { m_last_event.empty() ? std::string{} : std::format(", after \"{}\"", m_last_event), invariant.explain(Vehicle))); } } - m_before = {Time, Vehicle.V, Vehicle.DistCounter}; + m_before = {Time, Vehicle.V(), Vehicle.DistCounter()}; m_sampled = true; m_figures.sample(Time, Vehicle); diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index 454978056..39c7049d2 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -41,12 +41,12 @@ std::vector const &invariants() { static std::vector const rules{ {"every value a number", [](auto const &M, double, auto const *) { - std::initializer_list const values{M.V, M.AccS, M.Ft, M.Fb, M.Im, M.Itot, M.EngineVoltage, + std::initializer_list const values{M.V(), M.AccS(), M.Ft, M.Fb, M.Im, M.Itot, M.EngineVoltage, M.enrot, M.brakePipe.Pressure(), M.brakes.cylinderPressure, M.brakes.independentCylinderPressure, M.mainPipe.Pressure(), M.air.MainReservoirPressure(), M.lowVoltage.BatteryVoltage()}; return std::ranges::all_of(values, [](double const Value) { return std::isfinite(Value); }); }, [](auto const &M) { - return values({{"V", M.V}, {"AccS", M.AccS}, {"Ft", M.Ft}, {"Fb", M.Fb}, {"Im", M.Im}, {"Itot", M.Itot}, {"EngineVoltage", M.EngineVoltage}, + return values({{"V", M.V()}, {"AccS", M.AccS()}, {"Ft", M.Ft}, {"Fb", M.Fb}, {"Im", M.Im}, {"Itot", M.Itot}, {"EngineVoltage", M.EngineVoltage}, {"enrot", M.enrot}, {"PipePress", M.brakePipe.Pressure()}, {"BrakePress", M.brakes.cylinderPressure}, {"LocBrakePress", M.brakes.independentCylinderPressure}, {"ScndPipePress", M.mainPipe.Pressure()}, {"Compressor", M.air.MainReservoirPressure()}, {"BatteryVoltage", M.lowVoltage.BatteryVoltage()}}); }}, @@ -103,20 +103,20 @@ std::vector const &invariants() { // the speed of the step is between the speeds at its ends, or a bit off it, as the movement is integrated; // through a standstill, down to none auto const dt{Time - Before->time}; - auto const covered{(M.DistCounter - Before->DistCounter) * 1000.0}; - auto const lowest{M.V * Before->V > 0.0 ? std::min(std::abs(M.V), std::abs(Before->V)) : 0.0}; - auto const highest{std::max(std::abs(M.V), std::abs(Before->V))}; + auto const covered{(M.DistCounter() - Before->distCounter) * 1000.0}; + auto const lowest{M.V() * Before->v > 0.0 ? std::min(std::abs(M.V()), std::abs(Before->v)) : 0.0}; + auto const highest{std::max(std::abs(M.V()), std::abs(Before->v))}; return covered >= lowest * dt * 0.9 - 0.01 && covered <= highest * dt * 1.1 + 0.01; }, - [](auto const &M) { return values({{"V", M.V}, {"DistCounter", M.DistCounter}}); }}, + [](auto const &M) { return values({{"V", M.V()}, {"DistCounter", M.DistCounter()}}); }}, {"no acceleration over 5 g", [](auto const &M, double Time, auto const *Before) { - return Before == nullptr || std::abs(M.V - Before->V) <= highest_acceleration * (Time - Before->time) + 0.01; + return Before == nullptr || std::abs(M.V() - Before->v) <= highest_acceleration * (Time - Before->time) + 0.01; }, - [](auto const &M) { return values({{"V", M.V}, {"AccS", M.AccS}}); }}, + [](auto const &M) { return values({{"V", M.V()}, {"AccS", M.AccS()}}); }}, {"hand brake applied, the wheels braked on the move", - [](auto const &M, double, auto const *) { return false == M.brakes.config.hasHandBrake || M.brakes.HandBrakePosition() == 0 || std::abs(M.V) < 0.5 || std::abs(M.Fb) > 0.0; }, - [](auto const &M) { return values({{"ManualBrakePos", M.brakes.HandBrakePosition()}, {"V", M.V}, {"Fb", M.Fb}}); }}, + [](auto const &M, double, auto const *) { return false == M.brakes.config.hasHandBrake || M.brakes.HandBrakePosition() == 0 || std::abs(M.V()) < 0.5 || std::abs(M.Fb) > 0.0; }, + [](auto const &M) { return values({{"ManualBrakePos", M.brakes.HandBrakePosition()}, {"V", M.V()}, {"Fb", M.Fb}}); }}, }; return rules; } diff --git a/tests/unit/invariants.h b/tests/unit/invariants.h index 59550633d..b319a23b4 100644 --- a/tests/unit/invariants.h +++ b/tests/unit/invariants.h @@ -12,8 +12,8 @@ namespace test { // what the rules over time need of the step before struct snapshot { double time; - double V; - double DistCounter; + double v; + double distCounter; }; // a rule of physics or of the vehicle's circuits, which holds for every vehicle after every step, whatever diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index 7de3a2bfc..b87c1576e 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -195,7 +195,7 @@ TEST_CASE("cab: a road vehicle moved across its road") { bus.step(test::track{0.15, 0.0, 0.0, 2, 1, 7.0}); REQUIRE(TestFlag(bus->CategoryFlag, 2)); CHECK(bus->ChangeOffsetH(0.5)); - CHECK(bus->OffsetTrackH == doctest::Approx(0.5)); + CHECK(bus->OffsetTrackH() == doctest::Approx(0.5)); // off the edge of the road CHECK_FALSE(bus->ChangeOffsetH(100.0)); vehicle eu07{definition::fiz("4e_v1/4e")}; diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index 8bbb0a18b..eadd5732f 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -587,7 +587,7 @@ TEST_CASE("collisions: a locomotive at its starting effort against a braked trai locomotive->DirectionForward(); } test::drive(driver, line, 10.0); - auto const start{empty->DistCounter}; + auto const start{empty->DistCounter()}; auto pushed{0.0}; auto worst{0.0}; auto const watch = [&]() { @@ -608,7 +608,7 @@ TEST_CASE("collisions: a locomotive at its starting effort against a braked trai test::drive(driver, line, 1.0); watch(); } - auto const rolled{(empty->DistCounter - start) * 1000.0}; + 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); @@ -666,10 +666,10 @@ TEST_CASE("collisions: a train propelling an empty wagon into a braked one in a for (int i = 0; i < 6; ++i) { add_loaded(train, consist::full_coupling, 15.0, 0.0); } - auto const start{empty->DistCounter}; + auto const start{empty->DistCounter()}; train.run(10.0, curve); MESSAGE(std::format("the empty 3WL: derailed {}, {}, rolled {:.2f} m", derailed(empty.physics()), empty->CollisionDerail == COLLISION_PUSHED_OFF ? "pushed off" : "not pushed off", - (empty->DistCounter - start) * 1000.0)); + (empty->DistCounter() - start) * 1000.0)); CHECK(empty->CollisionDerail == COLLISION_PUSHED_OFF); } @@ -900,10 +900,10 @@ TEST_CASE("collisions: a vehicle off the rails by the new model stays in the cha auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 10.0, 0.5)}; wagon->derail_in_collision(COLLISION_PUSHED_OFF, "for the test"); REQUIRE(derailed(wagon.physics())); - auto const before{wagon->TotalMass * wagon->V + locomotive->TotalMass * locomotive->V}; + 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}; + 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); @@ -1346,7 +1346,7 @@ train_damage damage_of(consist &Train) { 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; + energy += 0.5 * Train[i]->TotalMass * Train[i]->V() * Train[i]->V(); } return energy; } @@ -1488,15 +1488,15 @@ TEST_CASE("collisions: a pair parting at the start of the step isn't crushed (l0 vehicle->forces(dt); } REQUIRE((front->Couplers[VehicleEnd::rear].closing < 0.0) == parting); - back->V = 25.0 * kmh; + back->SetV(25.0 * kmh); for (auto *vehicle : {&front, &back}) { - vehicle->move({}, dt, (*vehicle)->Loc, 5.0); + vehicle->move({}, dt, (*vehicle)->Loc(), 5.0); } auto const crush{front->Couplers[VehicleEnd::rear].crush + back->Couplers[VehicleEnd::front].crush}; if (parting) { CHECK(crush == 0.0); // the legacy collision pushed them apart - CHECK(back->V < 25.0 * kmh); + CHECK(back->V() < 25.0 * kmh); } else { // closing in from a stand, the knock is a hit past the energy of the buffers diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index ac25866b9..930893627 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -239,7 +239,7 @@ TEST_CASE("commands: every command run on every real vehicle") { vehicle real{definition::fiz(path), 0.0, "test", 1}; // loading takes place where the command was given, which comes with the command (PutCommand). a // vehicle gets none before its first one, TCommand::Location is left uninitialised - real->CommandIn.Location = real->Loc; + real->CommandIn.Location = real->Loc(); auto done{false}; auto channels{state()}; channels.emplace_back("Done", [&done](auto const &) { return flag(done); }); @@ -515,21 +515,21 @@ TEST_CASE("commands: a wagon loaded and unloaded by commands, which repeat until // the game gives the commands of loading through PutCommand, with the place of the platform or the ramp SUBCASE("loading 12 tonnes of coal") { trace.mark("load"); - wagon->PutCommand("Load=Coal", 12, 0, wagon->Loc); + wagon->PutCommand("Load=Coal", 12, 0, wagon->Loc()); wagon.run(30.0); CHECK(wagon->LoadAmount() == doctest::Approx(12.0).epsilon(0.1)); CHECK(wagon->LoadType.name == "coal"); CHECK(wagon->CommandIn.Command == VehicleCommand::none); trace.mark("unload"); - wagon->PutCommand("UnLoad=Coal", 20, 0, wagon->Loc); + wagon->PutCommand("UnLoad=Coal", 20, 0, wagon->Loc()); wagon.run(200.0); CHECK(wagon->LoadAmount() == doctest::Approx(0.0)); CHECK(wagon->LoadType.name.empty()); trace.check(); } SUBCASE("a load the wagon doesn't take stays a command, not done") { - wagon->PutCommand("Load=passengers", 12, 0, wagon->Loc); + wagon->PutCommand("Load=passengers", 12, 0, wagon->Loc()); wagon.run(10.0); CHECK(wagon->LoadAmount() == doctest::Approx(0.0)); CHECK_FALSE(wagon->CommandIn.Command == VehicleCommand::none); @@ -541,7 +541,7 @@ TEST_CASE("commands: a wagon loaded and unloaded by commands, which repeat until CHECK(wagon->LastLoadChangeTime == doctest::Approx(0.0)); } SUBCASE("unloading an empty wagon isn't done either") { - wagon->PutCommand("UnLoad=Coal", 12, 0, wagon->Loc); + wagon->PutCommand("UnLoad=Coal", 12, 0, wagon->Loc()); wagon.run(10.0); CHECK_FALSE(wagon->CommandIn.Command == VehicleCommand::none); } diff --git a/tests/unit/test_consist.cpp b/tests/unit/test_consist.cpp index f3524f678..3dba41b68 100644 --- a/tests/unit/test_consist.cpp +++ b/tests/unit/test_consist.cpp @@ -68,7 +68,7 @@ TEST_CASE("consist: every real electric unit driven whole from its front cab") { test::drive_cycle(test::driving(train), test::track{0.15, 0.0, test::catenary_3kv}, *traces.front()); // every unit runs off and is braked to a stop, but the EN57, which doesn't get ready (COVERAGE.md) auto const &leading{train[0].physics()}; - CHECK((leading.DistCounter > 0.2 /* km */) != (std::string{unit.name} == "en57")); + CHECK((leading.DistCounter() > 0.2 /* km */) != (std::string{unit.name} == "en57")); CHECK(leading.Vel < 0.5); for (auto const &trace : traces) { trace->check(); diff --git a/tests/unit/test_consist_braking.cpp b/tests/unit/test_consist_braking.cpp index 85276f00f..6b9367407 100644 --- a/tests/unit/test_consist_braking.cpp +++ b/tests/unit/test_consist_braking.cpp @@ -96,7 +96,7 @@ TEST_CASE("consist braking: with the controller at neutral and the train release unit.step(10.0); REQUIRE(unit.cab().eimic == doctest::Approx(0.0)); for (auto *car : unit.cars) { - car->V = 10.0; // [m/s], above the speed the holding brake comes in at + car->SetV(10.0); // [m/s], above the speed the holding brake comes in at car->Vel = 36.0; } unit.blending.Update(unit.cab(), unit.cars, {}, 0.01); diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index 0879c2fae..b53f0f904 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -211,7 +211,7 @@ TEST_CASE("controls: reversing and changing the cab of a locomotive") { // the speed along the vehicle, its front ahead notch_up(scenario, 10, 1.5); scenario.wait(10.0); - CHECK(cab.V > 3.0); + CHECK(cab.V() > 3.0); notch_down(scenario); brake_to_stop(scenario); CHECK(stopped(scenario)); @@ -222,7 +222,7 @@ TEST_CASE("controls: reversing and changing the cab of a locomotive") { CHECK(cab.DirActive < 0); notch_up(scenario, 10, 1.5); scenario.wait(10.0); - CHECK(cab.V < -3.0); + CHECK(cab.V() < -3.0); notch_down(scenario); brake_to_stop(scenario); CHECK(stopped(scenario)); @@ -241,7 +241,7 @@ TEST_CASE("controls: reversing and changing the cab of a locomotive") { notch_up(scenario, 10, 1.5); scenario.wait(10.0); // forward from the rear cab is the vehicle's backward - CHECK(cab.V < -3.0); + CHECK(cab.V() < -3.0); notch_down(scenario); brake_to_stop(scenario); CHECK(stopped(scenario)); @@ -515,7 +515,7 @@ TEST_CASE("controls: a locomotive running into a standing wagon") { // the wagon derails where it stands auto const derailed{speed > 30.0}; CHECK(wagon.DamageFlag.HasAll(VehicleDamage::derailed) == derailed); - CHECK((std::abs(wagon.DistCounter) > 0.0001) != derailed); + CHECK((std::abs(wagon.DistCounter()) > 0.0001) != derailed); CHECK(stopped(scenario)); scenario.check(); } diff --git a/tests/unit/test_coupler_physics.cpp b/tests/unit/test_coupler_physics.cpp index 753bc4213..1c8cea768 100644 --- a/tests/unit/test_coupler_physics.cpp +++ b/tests/unit/test_coupler_physics.cpp @@ -519,7 +519,7 @@ TEST_CASE("coupler physics: with couplerphysics yes, only the pairs with a vehic } SUBCASE("one covered: both compute the pair physically") { // as the player's train closing in on the other one - moving->CouplerPhysics = true; + moving->SetCouplerPhysics(true); pair.run(1.0); CHECK(moving->coupler_physics_at(VehicleEnd::front)); CHECK(standing->coupler_physics_at(VehicleEnd::rear)); @@ -528,7 +528,7 @@ TEST_CASE("coupler physics: with couplerphysics yes, only the pairs with a vehic } SUBCASE("the setting off: the legacy model, covered or not") { flag_setting const off{Global.coupler_physics, false}; - moving->CouplerPhysics = true; + moving->SetCouplerPhysics(true); CHECK_FALSE(moving->coupler_physics_at(VehicleEnd::front)); } } diff --git a/tests/unit/test_derail_motion.cpp b/tests/unit/test_derail_motion.cpp index 57f7f47c5..70e6ec810 100644 --- a/tests/unit/test_derail_motion.cpp +++ b/tests/unit/test_derail_motion.cpp @@ -420,14 +420,14 @@ TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment n 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); + 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}; + auto const start{eu07vehicle->V()}; for (int step = 0; step < 20; ++step) { eu07vehicle.step(curve); } - auto const deceleration{(start - eu07vehicle->V) / 0.2}; + 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(); @@ -478,7 +478,7 @@ TEST_CASE("derail motion: with physics.derailment monitor and old the vehicle st 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)); + 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(); diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index b2c1e7759..1dffe2f66 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -61,17 +61,17 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { CHECK(eu07vehicle->Derailed == dr::outcome::overturned); CHECK_FALSE(eu07vehicle->lineBreaker.IsClosed()); // 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}; + 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}; + 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)); + 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}; @@ -127,7 +127,7 @@ TEST_CASE("derailment: the model of eu07.ini") { // far over its threshold the draw comes out at once CHECK(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(eu07vehicle->Derailed == dr::outcome::none); - CHECK(eu07vehicle->V == doctest::Approx(0.0).epsilon(0.01)); + CHECK(eu07vehicle->V() == doctest::Approx(0.0).epsilon(0.01)); } } @@ -156,11 +156,11 @@ TEST_CASE("derailment: a stopped derailed vehicle stays put on a gradient") { eu07vehicle.step(curve); } REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); - REQUIRE(eu07vehicle->V == 0.0); + 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; + still = still && eu07vehicle->V() == 0.0 && eu07vehicle->AccS() == 0.0; } CHECK(still); } @@ -178,23 +178,23 @@ TEST_CASE("derailment: a repaired vehicle is back on the rails") { repaired.step(curve); } REQUIRE(repaired->Derailed == dr::outcome::overturned); - REQUIRE(repaired->V == 0.0); + REQUIRE(repaired->V() == 0.0); repaired->repair_damage(); CHECK(repaired->DamageFlag.Empty()); CHECK(repaired->Derailed == dr::outcome::none); - CHECK(repaired->derailment_distance == 0.0); - CHECK(repaired->OffsetTrackH == 0.0); - CHECK(repaired->OffsetTrackV == 0.0); + CHECK(repaired->DerailmentDistance() == 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->SetV(fresh->V()); + repaired->SetAccS(0.0); repaired->Derail(TOO_HIGH_SPEED); fresh->Derail(TOO_HIGH_SPEED); REQUIRE(repaired->Derailed == dr::outcome::none); - auto const start{fresh->V}; + auto const start{fresh->V()}; REQUIRE(start > 10.0); for (int step = 0; step < 150; ++step) { repaired.step(straight); @@ -202,8 +202,8 @@ TEST_CASE("derailment: a repaired vehicle is back on the rails") { } // 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)); + 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 @@ -212,11 +212,11 @@ TEST_CASE("derailment: a repaired vehicle is back on the rails") { 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); + 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; + repaired->SetV(150.0 * kmh); curve.gradient = 0.0; for (int step = 0; step < 20; ++step) { repaired.step(curve); @@ -303,7 +303,7 @@ TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what t } CHECK(faster->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(faster->Derailed == dr::outcome::none); - CHECK(faster->V == doctest::Approx(0.0).epsilon(0.01)); + CHECK(faster->V() == doctest::Approx(0.0).epsilon(0.01)); } } diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp index 9658f4123..008a8fbe8 100644 --- a/tests/unit/test_dynamic_brake_diesel.cpp +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -52,10 +52,10 @@ definition st44_braking() { // the force of the brakes above at full effort at the speed of the vehicle double br285_limit(physics::Vehicle 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); + 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(physics::Vehicle const &Vehicle) { - return std::min(120000.0, 1200000.0 / std::abs(Vehicle.V)) * std::clamp(Vehicle.Vel / 40.0, 0.0, 1.0); + 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 @@ -249,14 +249,14 @@ TEST_CASE("diesel-electric dynamic brake: without a fade it brings the vehicle t scenario.act("EB+ to the stop"); controller_to(locomotive, 0); - for (int i = 0; i < 120 && locomotive.V != 0.0; ++i) { + for (int i = 0; i < 120 && locomotive.V() != 0.0; ++i) { scenario.wait(1.0); } CHECK(locomotive.brakes.cylinderPressure < 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.V() == 0.0); CHECK(locomotive.Ft == doctest::Approx(0.0)); } CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); diff --git a/tests/unit/test_figures.cpp b/tests/unit/test_figures.cpp index 7eb7429c9..1d9fa63c8 100644 --- a/tests/unit/test_figures.cpp +++ b/tests/unit/test_figures.cpp @@ -16,14 +16,14 @@ TEST_CASE("figures: a run split into parts by the events, each from the last ste vehicle eu07{definition::fiz("4e_v1/4e")}; test::figures figures; auto &physics{eu07.physics()}; - physics.V = 10.0; + physics.SetV(10.0); physics.brakePipe.SetPressure(5.0); figures.sample(0.0, physics); figures.mark("brake"); figures.mark("hard"); for (int i = 1; i <= 10; ++i) { - physics.V = 10.0 - i; - physics.DistCounter += 0.005; + physics.SetV(10.0 - i); + physics.SetDistCounter(physics.DistCounter() + 0.005); physics.brakePipe.SetPressure(3.5); physics.brakes.cylinderPressure = 0.4 * i; figures.sample(i, physics); diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index ca2dc48a8..36943bf84 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -111,7 +111,7 @@ void notch_up(physics::Vehicle &Cab) { // the power at the wheels [kW] double wheel_power(physics::Vehicle const &Vehicle) { - return std::abs(Vehicle.Ft * Vehicle.V) / 1000.0; + return std::abs(Vehicle.Ft * Vehicle.V()) / 1000.0; } // one step of 0.01 s, acknowledging the vigilance once a second @@ -342,7 +342,7 @@ TEST_CASE("genset: running from the catenary is the same with the keys") { auto const record = [](values &Values) { return std::vector{ {"Ft", [&Values](physics::Vehicle const &Vehicle) { Values.force.push_back(Vehicle.Ft); return Vehicle.Ft; }}, - {"V", [&Values](physics::Vehicle const &Vehicle) { Values.speed.push_back(Vehicle.V); return Vehicle.V; }}, + {"V", [&Values](physics::Vehicle const &Vehicle) { Values.speed.push_back(Vehicle.V()); return Vehicle.V(); }}, {"EngineVoltage", [&Values](physics::Vehicle const &Vehicle) { Values.voltage.push_back(Vehicle.EngineVoltage); return Vehicle.EngineVoltage; }}, {"Itot", [&Values](physics::Vehicle const &Vehicle) { Values.current.push_back(Vehicle.Itot); return Vehicle.Itot; }}, {"eimv_pr", [&Values](physics::Vehicle const &Vehicle) { Values.demand.push_back(Vehicle.inductionMotor.forceShare); return Vehicle.inductionMotor.forceShare; }}, @@ -645,16 +645,16 @@ TEST_CASE("genset: a scenery command reaches the selector") { auto &cab{dragon6.physics()}; wake(cab); // as a scenery's PutValues event gives it, one at a time - cab.PutCommand("TractionMode", 1, 0, cab.Loc); + cab.PutCommand("TractionMode", 1, 0, cab.Loc()); dragon6.step(no_wire); CHECK(cab.GensetSelected()); CHECK(cab.CommandIn.Command == VehicleCommand::none); - cab.PutCommand("GensetSwitch", 1, 0, cab.Loc); + 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); + cab.PutCommand("TractionMode", 0, 0, cab.Loc()); dragon6.step(no_wire); CHECK_FALSE(cab.GensetSelected()); } diff --git a/tests/unit/test_invariants.cpp b/tests/unit/test_invariants.cpp index 94f32e0ab..e06421b2a 100644 --- a/tests/unit/test_invariants.cpp +++ b/tests/unit/test_invariants.cpp @@ -27,7 +27,7 @@ TEST_CASE("invariants: a vehicle in an impossible state, reported once with its CHECK(violation.find("BrakePress=50") != std::string::npos); eu07->brakes.cylinderPressure = 0.0; - eu07->V = std::nan(""); + eu07->SetV(std::nan("")); trace.sample(0.03, eu07.physics()); CHECK(trace.violations().size() > 1); CHECK(trace.violations()[1].find("every value a number") != std::string::npos); diff --git a/tests/unit/test_odometer.cpp b/tests/unit/test_odometer.cpp index b3da8d792..ffb420bc3 100644 --- a/tests/unit/test_odometer.cpp +++ b/tests/unit/test_odometer.cpp @@ -68,8 +68,8 @@ TEST_CASE("odometer: a vehicle counts the distance it runs either way, as the se test::vehicle vehicle{test::definition::load("wagon"), velocity}; vehicle->Odometer.begin(123456.0, odometer::origin::saved); vehicle.run(10.0); - CHECK(vehicle->DistCounter > 0.05); - CHECK(vehicle->Odometer.km - 123456.0 == doctest::Approx(vehicle->DistCounter)); + CHECK(vehicle->DistCounter() > 0.05); + CHECK(vehicle->Odometer.km - 123456.0 == doctest::Approx(vehicle->DistCounter())); CHECK(vehicle->Odometer.start == 123456.0); CHECK(vehicle->Odometer.moved()); } diff --git a/tests/unit/test_queries.cpp b/tests/unit/test_queries.cpp index 871549e9b..65f12b72d 100644 --- a/tests/unit/test_queries.cpp +++ b/tests/unit/test_queries.cpp @@ -42,7 +42,7 @@ TEST_CASE("queries: the damage of a vehicle as the driver's panel describes it") } // flat wheels count as worn ones wagon->DamageFlag = {}; - wagon->WheelFlat = 6.0; + wagon->SetWheelFlat(6.0); CHECK(wagon->EngineDescription(0) == "Wheel wear"); // nothing else is described CHECK(wagon->EngineDescription(1) == "Invalid qualifier"); diff --git a/tests/unit/test_traction.cpp b/tests/unit/test_traction.cpp index 19b417bd0..2073fae32 100644 --- a/tests/unit/test_traction.cpp +++ b/tests/unit/test_traction.cpp @@ -35,7 +35,7 @@ TEST_CASE("traction: every real powered vehicle started up, driven to full power // barely move (COVERAGE.md); the cars of a unit taking their power from another car don't start alone if (real->lineBreaker.IsClosed()) { auto const crawls{path == "sm31_v1/411d" || path == "tem2_v2/tem2a"}; - CHECK((real->DistCounter > 0.2 /* km */) != crawls); + CHECK((real->DistCounter() > 0.2 /* km */) != crawls); // but the road vehicle, which a minute of full service only slows down CHECK((real->Vel < 0.5) != (path == "road/man/nl293")); } diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index a2a228a8a..e508025d4 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -311,7 +311,7 @@ pair::~pair() { void pair::find_neighbours() { // as TDynamicObject::update_neighbours() for (auto const &placed : m_vehicles) { - placed.owner->physics().Loc = TLocation{placed.position, 0.0, 0.0}; + placed.owner->physics().SetLoc(TLocation{placed.position, 0.0, 0.0}); } for (int i = 0; i < 2; ++i) { auto const &self{m_vehicles[i]}; diff --git a/tests/unit/vehicle.h b/tests/unit/vehicle.h index 51362d9c1..bd05572e8 100644 --- a/tests/unit/vehicle.h +++ b/tests/unit/vehicle.h @@ -116,7 +116,7 @@ public: double move(track const &Track, double Dt, TLocation const &Location, double Trainpipe); // vehicle speed in kilometres per hour, negative when moving backwards - double speed() const { return m_physics->V * 3.6; } + double speed() const { return m_physics->V() * 3.6; } private: std::unique_ptr m_physics; diff --git a/utilities/motiontelemetry.cpp b/utilities/motiontelemetry.cpp index e8995d716..8703cb41f 100644 --- a/utilities/motiontelemetry.cpp +++ b/utilities/motiontelemetry.cpp @@ -93,9 +93,9 @@ void motiontelemetry::update() if (conf.latposbased) local_acc.x -= glm::dot(acc, leftvector); else - local_acc.x -= t->Occupied()->AccN; + local_acc.x -= t->Occupied()->AccN(); - local_acc.y += glm::dot(acc, up) + t->Occupied()->AccVert * conf.axlebumpscale; + local_acc.y += glm::dot(acc, up) + t->Occupied()->AccVert() * conf.axlebumpscale; if (conf.fwdposbased) local_acc.z += glm::dot(acc, frontvector); @@ -130,7 +130,7 @@ void motiontelemetry::update() glm::dvec3 rot(asin(-frontvector.y), atan2(frontvector.x, frontvector.z), asin(sinroll)); - double velocity = t->Occupied()->V; + double velocity = t->Occupied()->V(); double yaw_vel = (rot.y - last_yaw) / dt; last_yaw = rot.y; diff --git a/utilities/uart.cpp b/utilities/uart.cpp index df6544776..84ec31419 100644 --- a/utilities/uart.cpp +++ b/utilities/uart.cpp @@ -452,7 +452,7 @@ void uart_input::poll() GLFW_PRESS, // TODO: pass correct entity id once the missing systems are in place 0); - simulation::Train->Occupied()->eimic_analog = desiredpercent; + simulation::Train->Occupied()->SetEimicAnalog(desiredpercent); } } if( true == conf.scndenable ) { diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index 15dc15dd2..6ced9b912 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -108,7 +108,7 @@ void TController::Activation() && ( BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic ) ) { occupied->brakes.pipeLimiterPressure = occupied->brakePipe.Pressure(); - occupied->ActFlowSpeed = 0; + occupied->SetActFlowSpeed(0); } BrakeLevelSet( occupied->brakes.HandlePosition() ); } @@ -508,8 +508,8 @@ void TController::DirectionInitial() if (occupied->Vel > EU07_AI_NOMOVEMENT) { // jeśli na starcie jedzie iDirection = iDirectionOrder = - occupied->V > 0 ? 1 : -1; // początkowa prędkość wymusza kierunek jazdy - DirectionForward(occupied->V * occupied->CabActive >= 0.0); // a dalej ustawienie nawrotnika + occupied->V() > 0 ? 1 : -1; // początkowa prędkość wymusza kierunek jazdy + DirectionForward(occupied->V() * occupied->CabActive >= 0.0); // a dalej ustawienie nawrotnika } CheckVehicles(); // sprawdzenie świateł oraz skrajnych pojazdów do skanowania }; @@ -717,7 +717,7 @@ TController::determine_consist_state() { { // sprawdzenie odhamowania wszystkich połączonych pojazdów auto *vehicle { p->physics }; auto const bp { std::max( 0.0, vehicle->brakes.cylinderPressure - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->brakes.config.maxCylinderPressure[ 0 ] * vehicle->brakes.holding.deceleration : 0.0 ) ) }; - momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); + momentum += vehicle->TotalMass * vehicle->V() * ( p->DirectionGet() == iDirection ? 1 : -1 ); mostapplied = std::max( bp, mostapplied ); if( ( vehicle->brakes.config.kind != TBrakeSystem::Individual ) && ( vehicle->brakes.config.maxCylinderPressure[ 3 ] > 0.0 ) @@ -837,7 +837,7 @@ TController::determine_consist_state() { absaccs = 0; auto *d = pVehicles[ VehicleEnd::front ]; // pojazd na czele składu while( d ) { - absaccs += d->physics->TotalMass * d->physics->AccS * ( d->DirectionGet() == iDirection ? 1 : -1 ); + absaccs += d->physics->TotalMass * d->physics->AccS() * ( d->DirectionGet() == iDirection ? 1 : -1 ); d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) } absaccs *= iDirection >= 0 ? 1 : -1; diff --git a/vehicle/ai/driver.cpp b/vehicle/ai/driver.cpp index 056d0e7a5..57efaa96f 100644 --- a/vehicle/ai/driver.cpp +++ b/vehicle/ai/driver.cpp @@ -334,7 +334,7 @@ TController::Update( double const Timedelta ) { if( occupied->Vel > 1.0 ) { // przy prowadzeniu samochodu trzeba każdą oś odsuwać oddzielnie, inaczej kicha wychodzi if (occupied->CategoryFlag & 2) // jeśli samochód - // if (fabs(occupied->OffsetTrackH)Dim.W) //Ra: szerokość drogi tu powinna być? + // if (fabs(occupied->OffsetTrackH())Dim.W) //Ra: szerokość drogi tu powinna być? if (!occupied->ChangeOffsetH(-0.01 * occupied->Vel * dt)) // ruch w poprzek drogi occupied->ChangeOffsetH(0.01 * occupied->Vel * dt); // Ra: co to miało być, to nie wiem } @@ -578,7 +578,7 @@ bool TController::has_diesel_engine() const { return mvControlling->EngineType == TEngineType::DieselElectric || mvControlling->EngineType == TEngineType::DieselEngine; } double TController::DirectionalVel() const { - return occupied->Vel * sign( iDirection * occupied->V ); } + return occupied->Vel * sign( iDirection * occupied->V() ); } std::vector DrivingFlags::ActiveNames() const { std::vector> const flags { diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index 3bb5d68f9..c49ef577d 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -437,7 +437,7 @@ TController::PrepareDirection() { } else { // ustalenie kierunku, gdy jedzie - iDirection = occupied->V >= 0 ? 1 : // jazda w kierunku sprzęgu 0 + iDirection = occupied->V() >= 0 ? 1 : // jazda w kierunku sprzęgu 0 -1; // jazda w kierunku sprzęgu 1 } } diff --git a/vehicle/ai/obstacles.cpp b/vehicle/ai/obstacles.cpp index b0ef203b7..d1e4f660f 100644 --- a/vehicle/ai/obstacles.cpp +++ b/vehicle/ai/obstacles.cpp @@ -373,12 +373,12 @@ TController::scan_obstacles( double const Range ) { // HACK: vehicle order in the consist is based on intended travel direction // if our actual travel direction doesn't match that, we should be scanning from the other end of the consist // we cast to int to avoid getting confused by microstutters - auto *frontvehicle { pVehicles[ ( static_cast( occupied->V ) * iDirection >= 0 ? VehicleEnd::front : VehicleEnd::rear ) ] }; + auto *frontvehicle { pVehicles[ ( static_cast( occupied->V() ) * iDirection >= 0 ? VehicleEnd::front : VehicleEnd::rear ) ] }; int routescandirection; // for moving vehicle determine heading from velocity; for standing fall back on the set direction - if( std::abs(frontvehicle->physics->V) > 0.5 ? // ignore potential micro-stutters in oposite direction during "almost stop" - frontvehicle->physics->V > 0.0 : + if( std::abs(frontvehicle->physics->V()) > 0.5 ? // ignore potential micro-stutters in oposite direction during "almost stop" + frontvehicle->physics->V() > 0.0 : pVehicle->DirectionGet() == frontvehicle->DirectionGet() ? iDirection >= 0 : iDirection <= 0 ) { // towards coupler 0 routescandirection = NumberOf( VehicleEnd::front ); diff --git a/vehicle/ai/orders.cpp b/vehicle/ai/orders.cpp index 34e4f44b7..8f8160dd6 100644 --- a/vehicle/ai/orders.cpp +++ b/vehicle/ai/orders.cpp @@ -176,7 +176,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N { // SHP wyzwalane jest przez człon z obsadą, ale obsługiwane przez silnikowy // nie jest to najlepiej zrobione, ale bez symulacji obwodów lepiej nie będzie // Ra 2014-04: jednak przeniosłem do rozrządczego - occupied->PutCommand(NewCommand, NewValue1, NewValue2, occupied->Loc); + occupied->PutCommand(NewCommand, NewValue1, NewValue2, occupied->Loc()); occupied->RunInternalCommand(); // rozpoznaj komende bo lokomotywa jej nie rozpoznaje return true; // załatwione } @@ -192,7 +192,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N if (NewCommand == "Emergency_brake") // wymuszenie zatrzymania, niezależnie kto prowadzi { // Ra: no nadal nie jest zbyt pięknie // SetVelocity(0, 0, reason); - occupied->PutCommand("Emergency_brake", 1.0, 1.0, occupied->Loc); + occupied->PutCommand("Emergency_brake", 1.0, 1.0, occupied->Loc()); return true; // załatwione } @@ -301,8 +301,8 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N else if (!iDirectionOrder) {//jeśli nie ma kierunku, trzeba ustalić - if (occupied->V!=0.0) - iDirectionOrder=occupied->V>0?1:-1; + if (occupied->V()!=0.0) + iDirectionOrder=occupied->V()>0?1:-1; else iDirectionOrder=occupied->CabOccupied(); if (!iDirectionOrder) iDirectionOrder=1; @@ -310,7 +310,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N */ // jeśli wysyłane z Trainset, to wszystko jest już odpowiednio ustawione // if (!NewLocation) //jeśli wysyłane z Trainset - // if (occupied->CabActive*occupied->V*NewValue1<0) //jeśli zadana prędkość niezgodna z + // if (occupied->CabActive*occupied->V()*NewValue1<0) //jeśli zadana prędkość niezgodna z // aktualnym kierunkiem jazdy // DirectionForward(false); //jedziemy do tyłu (nawrotnik do tyłu) // CheckVehicles(); //sprawdzenie składu, AI zapali światła diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp index 83ad149e4..a3526b117 100644 --- a/vehicle/ai/physicslog.cpp +++ b/vehicle/ai/physicslog.cpp @@ -66,7 +66,7 @@ std::string TController::physicslog_line() const { line << std::fixed << std::setprecision( 4 ) << ElapsedTime << " " << fabs(11.31 * occupied->WheelDiameter * occupied->nrot) << " " - << mvControlling->AccS << " " + << mvControlling->AccS() << " " << occupied->Couplers[1].Dist << " " << occupied->Couplers[1].CForce << " " << occupied->Ft << " " @@ -90,7 +90,7 @@ std::string TController::physicslog_line() const { << mvControlling->diesel.heat.temperatura1 << " " << mvControlling->diesel.heat.temperatura2 << " " // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid - << occupied->V * 3.6 + << occupied->V() * 3.6 << "\r\n"; return line.str(); } @@ -116,7 +116,7 @@ void TController::PhysicsLog() std::ostringstream line; line << ElapsedTime << "\t" << fabs(11.31 * occupied->WheelDiameter * occupied->nrot) << "\t"; - line << mvControlling->AccS << "\t"; + line << mvControlling->AccS() << "\t"; line << occupied->brakePipe.Pressure() << "\t" << occupied->brakes.controlReservoirPressure << "\t" << occupied->brakes.cylinderPressure << "\t"; line << occupied->brakes.reservoirAir << "\t" << occupied->brakes.distributor->GetCRP() << "\n"; diff --git a/vehicle/ai/routescan.cpp b/vehicle/ai/routescan.cpp index fee849e3a..8974dd42d 100644 --- a/vehicle/ai/routescan.cpp +++ b/vehicle/ai/routescan.cpp @@ -211,7 +211,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) fTrackLength -= glm::length( pVehicle->AxlePositionGet() - pVehicle->RearPosition() - + pVehicle->VectorLeft() * pVehicle->physics->OffsetTrackH ); + + pVehicle->VectorLeft() * pVehicle->physics->OffsetTrackH() ); // aktualna odległość ma być ujemna gdyż jesteśmy na końcu składu fCurrentDistance = -fLength - fTrackLength; fTrackLength = pTrack->Length(); //skasowanie zmian w zmiennej żeby poprawnie liczyło w dalszych krokach diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index 01e98e40b..01453ec32 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -566,7 +566,7 @@ void TController::UpdateNextStop() { if( fLastStopExpDist > 0.0 - && occupied->DistCounter > fLastStopExpDist ) { + && occupied->DistCounter() > fLastStopExpDist ) { // zaktualizować wyświetlanie rozkładu TrainParams.StationStart = TrainParams.StationIndex; fLastStopExpDist = -1.0; // usunąć licznik diff --git a/vehicle/ai/speedtable.cpp b/vehicle/ai/speedtable.cpp index c778c3199..0fb84deae 100644 --- a/vehicle/ai/speedtable.cpp +++ b/vehicle/ai/speedtable.cpp @@ -350,7 +350,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute, asNextStop)); // informacja #endif // przy jakim dystansie (stanie licznika) ma przesunąć na następny postój - fLastStopExpDist = occupied->DistCounter + 0.250 + 0.001 * fLength; + fLastStopExpDist = occupied->DistCounter() + 0.250 + 0.001 * fLength; TrainParams.UpdateMTable( simulation::Time, asNextStop ); record_station( Point, blackbox::station_kinds::passed ); UpdateDelayFlag(); @@ -517,7 +517,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub IsAtPassengerStop = false; record_station( Point, blackbox::station_kinds::ready ); // przy jakim dystansie (stanie licznika) ma przesunąć na następny postój - fLastStopExpDist = occupied->DistCounter + 0.050 + 0.001 * fLength; + fLastStopExpDist = occupied->DistCounter() + 0.050 + 0.001 * fLength; TrainParams.StationIndexInc(); // przejście do następnej asNextStop = TrainParams.NextStop(); // pobranie kolejnego miejsca zatrzymania #if LOGSTOPS diff --git a/vehicle/cab/cabcommands.cpp b/vehicle/cab/cabcommands.cpp index d0be85a5e..6d385f9d8 100644 --- a/vehicle/cab/cabcommands.cpp +++ b/vehicle/cab/cabcommands.cpp @@ -638,13 +638,13 @@ void TTrain::OnCommand_vehicleboost(TTrain *Train, const command_data &Command) auto *vehicle{Train->DynamicObject}; while (vehicle) { - vehicle->physics->V += vehicle->DirectionGet() * boost; + vehicle->physics->SetV(vehicle->physics->V() + vehicle->DirectionGet() * boost); vehicle = vehicle->Next(); // pozostałe też } vehicle = Train->DynamicObject->Prev(); while (vehicle) { - vehicle->physics->V += vehicle->DirectionGet() * boost; + vehicle->physics->SetV(vehicle->physics->V() + vehicle->DirectionGet() * boost); vehicle = vehicle->Prev(); // w drugą stronę też } } diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 9d9df0c45..09fb91d76 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -264,7 +264,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("tractionforce", std::abs(occupied->Ft)); dict->insert("slipping_wheels", occupied->SlippingWheels); dict->insert("sanding", occupied->SandDose); - dict->insert("odometer", occupied->DistCounter); // distance run in the session, km + dict->insert("odometer", occupied->DistCounter()); // distance run in the session, km dict->insert("odometer_total", occupied->Odometer.km); // the vehicle's odometer, kept between the sessions // electric current data dict->insert("traction_voltage", std::abs(pantographUnit->pantographCircuit.SupplyVoltage())); @@ -418,7 +418,7 @@ TTrain::state_t TTrain::get_state() const fHVoltage, {fHCurrent[controlled->TrainType == train_type::emu ? 0 : 1], fHCurrent[2], fHCurrent[3]}, ggLVoltage.GetValue(), - occupied->DistCounter, + occupied->DistCounter(), static_cast(RadioChannel()), btLampkaSpringBrakeActive.GetValue(), btLampkaNapNastHam.GetValue(), diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 61d9dd681..4adf31f90 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -1208,7 +1208,7 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) { set_master_controller(Console::AnalogCalibrateGet(2) * occupied->MainCtrlPosNo); - occupied->eimic_analog = Console::AnalogCalibrateGet(2); + occupied->SetEimicAnalog(Console::AnalogCalibrateGet(2)); } #endif diff --git a/vehicle/dynamic/consist.cpp b/vehicle/dynamic/consist.cpp index f5141d3be..1bde532dd 100644 --- a/vehicle/dynamic/consist.cpp +++ b/vehicle/dynamic/consist.cpp @@ -292,7 +292,7 @@ TDynamicObject::update_neighbours() { // NOTE: we perform a new scan on each update to ensure we always locate the nearest potential source 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( physics->V ) ) + 40.0 }; + auto const scanrange { std::max( 10.0, std::abs( physics->V() ) ) + 40.0 }; // 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( NumberOf( end ), scanrange, true ) }; @@ -519,9 +519,9 @@ TDynamicObject *TDynamicObject::PrevConnected() const { return physics->Neighbou int TDynamicObject::NextConnectedNo() const { return physics->Neighbours[ VehicleEnd::rear ].vehicle_end; } int TDynamicObject::PrevConnectedNo() const { return physics->Neighbours[ VehicleEnd::front ].vehicle_end; } -void TDynamicObject::SetdMoveLen( double dMoveLen ) { physics->dMoveLen = dMoveLen; } -void TDynamicObject::ResetdMoveLen() { physics->dMoveLen = 0; } -double TDynamicObject::GetdMoveLen() { return physics->dMoveLen; } +void TDynamicObject::SetdMoveLen( double dMoveLen ) { physics->SetMoveLength(dMoveLen); } +void TDynamicObject::ResetdMoveLen() { physics->SetMoveLength(0); } +double TDynamicObject::GetdMoveLen() { return physics->MoveLength(); } double TDynamicObject::GetVelocity() const { return physics->Vel; } double TDynamicObject::GetLength() const { return physics->Dim.L; } diff --git a/vehicle/dynamic/couplers.cpp b/vehicle/dynamic/couplers.cpp index 911aee242..43de745b6 100644 --- a/vehicle/dynamic/couplers.cpp +++ b/vehicle/dynamic/couplers.cpp @@ -321,10 +321,10 @@ void TDynamicObject::AttachNext(TDynamicObject *Object, int iType) Object->Move( physics->Neighbours[ vehicleend ].distance * Object->DirectionGet() ); // HACK: manually update vehicle position as it's used by neighbour distance update we do next - Object->physics->Loc = { + Object->physics->SetLoc({ -Object->vPosition.x, Object->vPosition.z, - Object->vPosition.y }; + Object->vPosition.y }); // update neighbour distance data after moving our vehicle update_neighbours(); Object->update_neighbours(); diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index 64416967f..9fac4a7b1 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -169,7 +169,7 @@ void TDynamicObject::place_on_track(TTrack *Track, double fDist, bool Reversed) } // the stretches the criteria of derailment held over were on the track the vehicle left (consistteleport) physics->derailment_monitor.reset(); - physics->derailment_distance = 0.0; + physics->SetDerailmentDistance(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 @@ -454,7 +454,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" auto const indexstart { 1 }; auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; auto const huntingchance { std::atoi( ActPar.substr( indexstart, indexend ).c_str() ) }; - physics->TruckHunting = Random(0, 100) < huntingchance; + physics->SetTruckHunting(Random(0, 100) < huntingchance); ActPar.erase( 0, indexend ); break; } @@ -466,7 +466,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" } } if( Random( 0, 100 ) <= flatchance ) { - physics->WheelFlat += fixedflatsize + Random( 0, randomflatsize ); + physics->SetWheelFlat( physics->WheelFlat() + ( fixedflatsize + Random( 0, randomflatsize ) ) ); } } // wheel else if( ActPar.size() >= 2 @@ -534,23 +534,22 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" { // ustawianie samochodow na poboczu albo na środku drogi if( Track->fTrackWidth < 3.5 // jeśli droga wąska || Track->m_road != nullptr ) // a lane of a road node is one-way, the vehicle keeps to its middle - physics->OffsetTrackH = 0.0; // to stawiamy na środku, niezależnie od stanu + physics->SetOffsetTrackH(0.0); // to stawiamy na środku, niezależnie od stanu // ruchu else if( driveractive ) {// od 3.5m do 8.0m jedzie po środku pasa, dla // szerszych w odległości // 1.5m auto const lanefreespace = 0.5 * Track->fTrackWidth - physics->Dim.W; - physics->OffsetTrackH = lanefreespace > 1.5 ? + physics->SetOffsetTrackH(lanefreespace > 1.5 ? -0.5 * physics->Dim.W - 0.75 : // wide road, keep near centre with safe margin lanefreespace > 0.1 ? -0.25 * Track->fTrackWidth : // narrow fit, stay on the middle - -0.5 * physics->Dim.W - 0.075; // too narrow, just keep some minimal clearance + -0.5 * physics->Dim.W - 0.075); // too narrow, just keep some minimal clearance } else // jak stoi, to kołem na poboczu i pobieramy szerokość razem z // poboczem, ale nie z // chodnikiem - physics->OffsetTrackH = - -0.5 * (Track->WidthTotal() - physics->Dim.W) + 0.05; + physics->SetOffsetTrackH(-0.5 * (Track->WidthTotal() - physics->Dim.W) + 0.05); iHornWarning = 0; // nie będzie trąbienia po podaniu zezwolenia na jazdę if (fDist < 0.0) //-0.5*physics->Dim.L) //jeśli jest przesunięcie do tyłu if (!Track->CurrentPrev()) // a nie ma tam odcinka i trzeba by coś @@ -754,10 +753,10 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" Move( 0.0001 ); ABuCheckMyTrack(); // zmiana toru na ten, co oś Axle0 (oś z przodu) // Ra: ustawienie pozycji do obliczania sprzęgów - physics->Loc = { + physics->SetLoc({ -vPosition.x, vPosition.z, - vPosition.y }; // normalnie przesuwa ComputeMovement() w Update() + vPosition.y }); // normalnie przesuwa ComputeMovement() w Update() // ABuWozki 060504 if (mdModel) // jeśli ma w czym szukać { @@ -869,7 +868,7 @@ TDynamicObject::create_controller( std::string const Type, bool const Trainset ) // tryb pociągowy z ustaloną prędkością (względem sprzęgów) Mechanik->PutCommand( "Timetable:", - physics->V * 3.6 * ( iDirection ? -1.0 : 1.0 ), + physics->V() * 3.6 * ( iDirection ? -1.0 : 1.0 ), 0, nullptr ); } diff --git a/vehicle/dynamic/lights.cpp b/vehicle/dynamic/lights.cpp index b531cd9c0..0549ff63f 100644 --- a/vehicle/dynamic/lights.cpp +++ b/vehicle/dynamic/lights.cpp @@ -256,7 +256,7 @@ TDimension const &TDynamicObject::Dimensions() const { } double TDynamicObject::Speed() const { - return physics->V; + return physics->V(); } int TDynamicObject::ActiveCab() const { diff --git a/vehicle/dynamic/movement.cpp b/vehicle/dynamic/movement.cpp index 0cccff345..456033b0e 100644 --- a/vehicle/dynamic/movement.cpp +++ b/vehicle/dynamic/movement.cpp @@ -60,7 +60,7 @@ http://mozilla.org/MPL/2.0/. void TDynamicObject::FastMove(double fDistance) { - physics->dMoveLen = physics->dMoveLen + fDistance; + physics->SetMoveLength(physics->MoveLength() + fDistance); } void TDynamicObject::Move(double fDistance) @@ -90,7 +90,7 @@ void TDynamicObject::move_axles(double fDistance) // na tym samym torze if (physics->Vel > 2) //|[km/h]| nie ma sensu zmiana osi, jesli pojazd drga na postoju - iAxleFirst = physics->V >= 0.0 ? + iAxleFirst = physics->V() >= 0.0 ? 1 : 0; //[m/s] ?1:0 - aktywna druga oś w kierunku jazdy // aktualnie eventy aktywuje druga oś, żeby AI nie wyłączało sobie semafora @@ -148,10 +148,10 @@ void TDynamicObject::place_by_axles() mMatrix = glm::inverse(mMatrix); // wyliczenie macierzy dla pojazdu (potrzebna tylko do wyświetlania?) // if (physics->CategoryFlag&2) { // przesunięcia są używane po wyrzuceniu pociągu z toru - vPosition.x += physics->OffsetTrackH * vLeft.x; // dodanie przesunięcia w bok - vPosition.z += physics->OffsetTrackH * vLeft.z; // vLeft jest wektorem poprzecznym + vPosition.x += physics->OffsetTrackH() * vLeft.x; // dodanie przesunięcia w bok + vPosition.z += physics->OffsetTrackH() * vLeft.z; // vLeft jest wektorem poprzecznym // if () na przechyłce będzie dodatkowo zmiana wysokości samochodu - vPosition.y += physics->OffsetTrackV; // te offsety są liczone przez the physics + vPosition.y += physics->OffsetTrackV(); // te offsety są liczone przez the physics } // obliczanie pozycji sprzęgów do liczenia zderzeń auto dir = 0.5 * physics->Dim.L * vFront; // wektor sprzęgu diff --git a/vehicle/dynamic/neighbours.cpp b/vehicle/dynamic/neighbours.cpp index dc24a84a5..9d9d97945 100644 --- a/vehicle/dynamic/neighbours.cpp +++ b/vehicle/dynamic/neighbours.cpp @@ -293,10 +293,10 @@ TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const double relativeoffset; // wzajemna odległość poprzeczna if( Foundcoupler != Mycoupler ) { // facing the same direction - relativeoffset = std::abs( physics->OffsetTrackH - dynamic->physics->OffsetTrackH ); + relativeoffset = std::abs( physics->OffsetTrackH() - dynamic->physics->OffsetTrackH() ); } else { - relativeoffset = std::abs( physics->OffsetTrackH + dynamic->physics->OffsetTrackH ); + relativeoffset = std::abs( physics->OffsetTrackH() + dynamic->physics->OffsetTrackH() ); } if( relativeoffset + relativeoffset > physics->Dim.W + dynamic->physics->Dim.W ) { // odległość większa od połowy sumy szerokości - kolizji nie będzie diff --git a/vehicle/dynamic/offtrack.cpp b/vehicle/dynamic/offtrack.cpp index e12ccb0c2..5b6b16fc9 100644 --- a/vehicle/dynamic/offtrack.cpp +++ b/vehicle/dynamic/offtrack.cpp @@ -246,7 +246,7 @@ void TDynamicObject::gather_off_track_terrain() { auto const &position { physics->OffTrack.active() ? physics->OffTrack.current().position : vPosition }; // as far as it may slide, and some - auto const slide { derail_motion::stopping_distance( physics->V, derailment::off_rails_friction ).value_or( 0.0 ) }; + auto const slide { derail_motion::stopping_distance( physics->V(), derailment::off_rails_friction ).value_or( 0.0 ) }; auto const reach { std::min( slide + physics->Dim.L + 50.0, 600.0 ) }; m_offtrackgathered = m_offtracktotal; m_offtrackcropped = false; @@ -257,7 +257,7 @@ void TDynamicObject::gather_off_track_terrain() { heading = physics->OffTrack.heading(); } auto const length { glm::length( heading ) }; - auto const stop { length > 1e-6 ? position + heading * ( std::copysign( std::max( reach - physics->Dim.L - 50.0, 0.0 ), physics->V ) / length ) : position }; + auto const stop { length > 1e-6 ? position + heading * ( std::copysign( std::max( reach - physics->Dim.L - 50.0, 0.0 ), physics->V() ) / length ) : position }; auto const margin { physics->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 }, @@ -334,7 +334,7 @@ void TDynamicObject::begin_off_track() { start.position = vPosition; start.front = vFront; start.line = track_front(); - start.speed = physics->V; + start.speed = physics->V(); start.reason = physics->DerailCause; start.outward = ( physics->DerailSide != 0 ? physics->DerailSide : outward_side() ); start.acceleration = physics->DerailAcceleration; @@ -361,7 +361,7 @@ void TDynamicObject::begin_off_track() { } 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", - physics->Name, std::abs( physics->V ) * 3.6, MyTrack != nullptr ? MyTrack->name() : std::string { "(none)" }, + physics->Name, std::abs( physics->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}{}", @@ -397,10 +397,10 @@ void TDynamicObject::move_off_track( double const Distance ) { derail_motion::meet( end_point_of( *this, end ), end_point_of( *neighbour, physics->Neighbours[ end ].FacingEnd() ) ), compression ); } auto const reversals { motion.reversals() }; - motion.step( time, Distance, physics->V, m_offtracksite, ends ); + motion.step( time, Distance, physics->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 - physics->V = -physics->V; + physics->SetV(-physics->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 @@ -497,6 +497,6 @@ void TDynamicObject::update_off_track( double const Deltatime ) { 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{}", - physics->Name, resting ? "came to rest" : "off the track", motion.travelled(), off_track_offset(), std::abs( physics->V ) * 3.6, motion.sideways(), + physics->Name, resting ? "came to rest" : "off the track", motion.travelled(), off_track_offset(), std::abs( physics->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" : "" ) ); } diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index e5bccba88..c751bbb24 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -763,10 +763,10 @@ void TDynamicObject::renderWheelFlatSound() { if( physics->CategoryFlag == 1 ) { // trains only if( GetVelocity() > 1.0 - && physics->WheelFlat > 5.0 ) { + && physics->WheelFlat() > 5.0 ) { m_wheelflat .pitch( m_wheelflat.m_frequencyoffset + std::abs( physics->nrot ) * m_wheelflat.m_frequencyfactor ) - .gain( m_wheelflat.m_amplitudeoffset + m_wheelflat.m_amplitudefactor * ( ( 1.0 + physics->Vel / physics->Vmax + std::clamp( physics->WheelFlat / 60.0, 0.0, 1.0 ) ) / 3.0 ) ) + .gain( m_wheelflat.m_amplitudeoffset + m_wheelflat.m_amplitudefactor * ( ( 1.0 + physics->Vel / physics->Vmax + std::clamp( physics->WheelFlat() / 60.0, 0.0, 1.0 ) ) / 3.0 ) ) .play( sound_flags::exclusive | sound_flags::looping ); } else { @@ -786,7 +786,7 @@ void TDynamicObject::renderCurveSound() { && std::abs(ts.R) < 15000.0 ) { // scale volume with curve radius and vehicle speed volume = - std::abs( physics->AccN ) // * physics->AccN + std::abs( physics->AccN() ) // * physics->AccN() * std::lerp( 0.5, 1.0, std::clamp( @@ -817,7 +817,7 @@ void TDynamicObject::renderStartJoltSound() { // movement start jolt if( false == m_startjoltplayed ) { auto const velocity { GetVelocity() }; - if( ( physics->V > 0.0 ? physics->AccSVBased > 0.1 : physics->AccSVBased < 0.1 ) + if( ( physics->V() > 0.0 ? physics->AccSVBased > 0.1 : physics->AccSVBased < 0.1 ) && velocity > 1.0 && velocity < 15.0 ) { m_startjolt.play( sound_flags::exclusive ); diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index f21a5241b..9968a9b35 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -170,10 +170,10 @@ bool TDynamicObject::Update(double dt, double dt1) toggle_lights(); } - if (physics->InactiveCabPantsCheck) + if (physics->InactiveCabPantsCheck()) { pants_up(); - physics->InactiveCabPantsCheck = false; + physics->SetInactiveCabPantsCheck(false); } if( physics->LoadStatus() ) { @@ -237,10 +237,10 @@ void TDynamicObject::updateCouplingState() // couplers if( physics->Couplers[0].CouplingFlag != Coupling::none && physics->Couplers[1].CouplingFlag != Coupling::none ) { - physics->InsideConsist = true; + physics->SetInsideConsist(true); } else { - physics->InsideConsist = false; + physics->SetInsideConsist(false); } if( TestFlag( physics->AIFlag, sound::attachcoupler ) ) { auto *driver{ ctOwner ? ctOwner : Mechanik }; @@ -478,7 +478,7 @@ void TDynamicObject::applyJointJolt( int const axleindex ) { // crude bump simulation, drop down on even axles, move back up on // the odd ones - // physics->AccVert += (physics->Vel*0.1f) * + // physics->AccVert() += (physics->Vel*0.1f) * // the arguments keep the order they had up to 26.05.1, 0 in place of the value and the figure in place of the // upper limit, so they work out as the old clamp worked them out up to 26.05.1: the headroom is // Vmax - (Vel + 0.32 Vmax) whatever its sign, and the bump is capped from above only @@ -486,14 +486,13 @@ void TDynamicObject::applyJointJolt( int const axleindex ) double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f ); if (MyTrack->eType == tt_Normal) { - physics->AccVert += safe_clamp( 0.0, 4.0, jolt ); + physics->ShakeVertically( safe_clamp( 0.0, 4.0, jolt ) ); } else if (MyTrack->eType == tt_Switch) { double const accHorizontal = safe_clamp( 0.0, 1.0, jolt ) * ((axleindex % 2) != 0 ? 1 : -1); - physics->AccS += accHorizontal; - physics->AccN += accHorizontal; - physics->AccVert += safe_clamp( 0.0, 2.0, jolt ); + physics->ShakeHorizontally( accHorizontal ); + physics->ShakeVertically( safe_clamp( 0.0, 2.0, jolt ) ); } } @@ -504,10 +503,10 @@ void TDynamicObject::updateWheelAngles( double const dt1 ) { // McZapkie-050402: krecenie kolami: glm::dvec3 old_wheels = glm::dvec3(dWheelAngle[0], dWheelAngle[1], dWheelAngle[2]); - dWheelAngle[0] += 114.59155902616464175359630962821 * physics->V * dt1 / + dWheelAngle[0] += 114.59155902616464175359630962821 * physics->V() * dt1 / physics->WheelDiameterL; // przednie toczne dWheelAngle[1] += physics->nrot * dt1 * 360.0; // napędne - dWheelAngle[2] += 114.59155902616464175359630962821 * physics->V * dt1 / + dWheelAngle[2] += 114.59155902616464175359630962821 * physics->V() * dt1 / physics->WheelDiameterT; // tylne toczne diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index f9698ae9a..0c5abdd14 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -147,10 +147,10 @@ vehicle_table::update_coupler_physics() const { std::unordered_set checked; for( auto *vehicle : m_items ) { if( covered.contains( vehicle ) ) { - vehicle->physics->CouplerPhysics = true; + vehicle->physics->SetCouplerPhysics(true); continue; } - if( false == vehicle->physics->CouplerPhysics + if( false == vehicle->physics->CouplerPhysics() || checked.contains( vehicle ) ) { continue; } @@ -159,7 +159,7 @@ vehicle_table::update_coupler_physics() const { checked.insert( other.begin(), other.end() ); if( false == trains_within( other, train, coupler_physics_release ) ) { for( auto *othervehicle : other ) { - othervehicle->physics->CouplerPhysics = false; + othervehicle->physics->SetCouplerPhysics(false); } } } @@ -388,7 +388,7 @@ derail_motion::contact_body contact_body_of( TDynamicObject const &Vehicle ) { 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 * physics.V; + body.velocity = body.guide * physics.V(); } return body; } @@ -471,7 +471,7 @@ vehicle_table::update_off_track_contacts( double const Deltatime ) { 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->physics->V = motion.speed(); + vehicle->physics->SetV(motion.speed()); } if( correction > 0.0 ) { motion.nudge( -hit->normal * ( share * correction ) ); @@ -482,7 +482,7 @@ vehicle_table::update_off_track_contacts( double const Deltatime ) { auto &othermotion { other->physics->OffTrack }; if( glm::length( impulse ) > 0.0 ) { othermotion.kick( othervelocity, otheryawrate ); - other->physics->V = othermotion.speed(); + other->physics->SetV(othermotion.speed()); } if( correction > 0.0 ) { othermotion.nudge( hit->normal * ( share * correction ) ); @@ -492,7 +492,7 @@ vehicle_table::update_off_track_contacts( double const Deltatime ) { } // one on the rails: along them into its speed, across them on its wheels, as a coupling pulls them off auto &otherPhysics { *other->physics }; - otherPhysics.V += glm::dot( impulse, otherbody.guide ) / std::max( otherPhysics.TotalMass, 1.0 ); + otherPhysics.SetV( otherPhysics.V() + glm::dot( impulse, otherbody.guide ) / std::max( otherPhysics.TotalMass, 1.0 ) ); if( otherPhysics.DamageFlag.HasAll(VehicleDamage::derailed) ) { continue; } diff --git a/vehicle/dynamic/visual.cpp b/vehicle/dynamic/visual.cpp index 0bb307857..49978348a 100644 --- a/vehicle/dynamic/visual.cpp +++ b/vehicle/dynamic/visual.cpp @@ -671,7 +671,7 @@ TDynamicObject::update_shake( double const Timedelta ) { } if( HuntingShake.fadein_begin > 0.f - && true == physics->TruckHunting ) { + && true == physics->TruckHunting() ) { // hunting oscillation HuntingAngle = clamp_circular( HuntingAngle + 4.0 * HuntingShake.frequency * Timedelta * physics->Vel, 360.0 ); auto const huntingamount = @@ -695,11 +695,11 @@ TDynamicObject::update_shake( double const Timedelta ) { if( iVel > 0.5 ) { // acceleration-driven base shake shakevector += glm::dvec3( - replaced.sway ? 0.0 : -physics->AccN * Timedelta * 5.0 * Global.ShakingMultiplierRL, // highlight side sway - -physics->AccVert * Timedelta * Global.ShakingMultiplierUD, + replaced.sway ? 0.0 : -physics->AccN() * Timedelta * 5.0 * Global.ShakingMultiplierRL, // highlight side sway + -physics->AccVert() * Timedelta * Global.ShakingMultiplierUD, -physics->AccSVBased * Timedelta * 1.5 * Global.ShakingMultiplierBF); // accent acceleration/deceleration // unevenness of the track under the outer axles - auto const ride { 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ) * ( physics->V * physics->V ) }; + auto const ride { 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ) * ( physics->V() * physics->V() ) }; shakevector += glm::dvec3( -glm::dot( ride, vLeft ) * Timedelta * 5.0 * Global.ShakingMultiplierRL, -ride.y * Timedelta * Global.ShakingMultiplierUD, diff --git a/widgets/trainingcard.cpp b/widgets/trainingcard.cpp index d5a464e92..3f2f5e0ff 100644 --- a/widgets/trainingcard.cpp +++ b/widgets/trainingcard.cpp @@ -179,7 +179,7 @@ void trainingcard_panel::render_contents() { state.store(2); if (simulation::Trains.sequence().size() > 0) - distance = static_cast(simulation::Trains.sequence()[0]->Dynamic()->physics->DistCounter); + distance = static_cast(simulation::Trains.sequence()[0]->Dynamic()->physics->DistCounter()); if (save_thread.joinable()) save_thread.join(); diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index 8d786f02b..d5ac18e45 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -228,9 +228,9 @@ void ui::vehicleparams_panel::render_contents() 0.001f, physics.Fb * 0.001f, physics.Adhesive(physics.RunningTrack.friction), (physics.SlippingWheels ? " (!)" : ""), // acceleration - physics.AccSVBased, physics.AccN + 0.001f, std::string(std::abs(physics.RunningShape.R) > 10000.0 ? "~0" : to_string(physics.RunningShape.R, 0)).c_str(), + physics.AccSVBased, physics.AccN() + 0.001f, std::string(std::abs(physics.RunningShape.R) > 10000.0 ? "~0" : to_string(physics.RunningShape.R, 0)).c_str(), // velocity - vehicle.GetVelocity(), physics.DistCounter, + vehicle.GetVelocity(), physics.DistCounter(), // position vehicle.GetPosition().x, vehicle.GetPosition().y, vehicle.GetPosition().z); @@ -293,7 +293,7 @@ void ui::vehicleparams_panel::render_contents() if (ImGui::IsItemDeactivated()) m_relay.post(user_command::consistreleaser, 0.0, 0.0, GLFW_RELEASE, 0, glm::vec3(0.0f), &vehicle_ptr->name()); - if (vehicle_ptr->physics->V < 0.01) + if (vehicle_ptr->physics->V() < 0.01) { if (ImGui::Button(STR_C("Move +500m"))) m_relay.post(user_command::dynamicmove, 500.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &vehicle_ptr->name()); diff --git a/world/Road.cpp b/world/Road.cpp index 39396b87f..f9b6cd137 100644 --- a/world/Road.cpp +++ b/world/Road.cpp @@ -3161,7 +3161,7 @@ void junction_node::update(double const Deltatime) if (first != nullptr) { gate.distance = nearest; - gate.speed = std::abs(first->physics->V); + gate.speed = std::abs(first->physics->V()); gate.halflength = 0.5 * first->physics->Dim.L; gate.taken = ways_of(gate, first); gate.active = gate.distance < std::max(gate_zone, gate.speed * gate_gap) + gate.halflength; diff --git a/world/RoadPoint.cpp b/world/RoadPoint.cpp index f3e8b89ba..5e5ed6ecb 100644 --- a/world/RoadPoint.cpp +++ b/world/RoadPoint.cpp @@ -860,7 +860,7 @@ void roadpoint_node::prepare() } pooled_vehicle entry; entry.vehicle = vehicle; - entry.velocity = vehicle->physics->V; + entry.velocity = vehicle->physics->V(); m_pool.emplace_back(entry); // ...which is taken off the road right away, the way the vehicles leaving the scenery are, to wait for its turn if (vehicle->MyTrack != nullptr) @@ -998,7 +998,7 @@ void roadpoint_node::update_spawn(double const Deltatime) entry.standing = 0.0; continue; } - auto const speed{vehicle->physics->V}; + auto const speed{vehicle->physics->V()}; // forward is the way it went when it was put on the road auto const backwards{speed * entry.velocity < 0.0 && std::abs(speed) > reverse_speed}; if (std::abs(speed) > stuck_speed || simulation::Roadpoints.holds(*vehicle)) @@ -1062,7 +1062,7 @@ void roadpoint_node::update_spawn(double const Deltatime) // it comes back the way it was made: whole, at speed, with the driver told to drive on vehicle->bEnabled = true; vehicle->physics->repair_damage(); - vehicle->physics->V = entry.velocity; + vehicle->physics->SetV(entry.velocity); vehicle->place_on_track(m_lanes.front(), m_offset + 0.5 * vehicle->physics->Dim.L, false); if (vehicle->Mechanik != nullptr) { From 439adc2f467707b6dbe4cb057f48876a9a2e620d Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 12:52:28 +0100 Subject: [PATCH 24/30] refactor(physics): the last outside writes into the vehicle go through operations What the AI, the cab and TDynamicObject still set in the physics directly is named now: the stabiliser of the brake pipe reset as a driver takes over a cab (ResetPipeStabiliser()), the spring brake released by hand (ReleaseSpringBrake()), the mode of the brake (SetBrakeOperatingMode()), the brake cut out by the player (ClaimBrakeCutOut()), the pressure of the consist's brake pipe (SetEquivalentPipePressure()), the inverters switched from the cab (SwitchInverter()), the odometer (SetOdometer(), ShowOdometer()). The state the pantographs' sounds last followed belonged to the sounds, not to the physics: it moves from basic_pantograph to TDynamicObject. Outside physics/ nothing writes into a vehicle's state any more but the definition the scenery and the .mmd adjust as the vehicle loads. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- physics/components/devices.h | 1 - physics/vehicle.h | 20 ++++++++++++++++++++ vehicle/DynObj.h | 2 ++ vehicle/ai/consist.cpp | 7 +++---- vehicle/cab/brakecommands.cpp | 2 +- vehicle/cab/equipmentcommands.cpp | 6 +++--- vehicle/cab/setup.cpp | 4 ++-- vehicle/dynamic/lifecycle.cpp | 2 +- vehicle/dynamic/update.cpp | 10 +++++----- 9 files changed, 37 insertions(+), 17 deletions(-) diff --git a/physics/components/devices.h b/physics/components/devices.h index f032bd84a..1b76e2971 100644 --- a/physics/components/devices.h +++ b/physics/components/devices.h @@ -132,7 +132,6 @@ struct basic_pantograph basic_valve valve; // associated pneumatic valve // ld outputs bool is_active{false}; // device is working - bool sound_event{false}; // indicates last state which generated sound event double voltage{0.0}; }; diff --git a/physics/vehicle.h b/physics/vehicle.h index bf1f66bcb..4d6cc4277 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -1710,6 +1710,26 @@ class Vehicle void FuseOff(void); // wylaczenie nadmiarowego // the faults of the equipment the scenery or the network sets: each sets its fault, or clears it where it was set void SetEquipmentFaults(EquipmentFaultSet Faults); + // the stabiliser of the brake pipe set to the pressure the pipe has, as a driver taking over a cab finds it + void ResetPipeStabiliser() + { + brakes.pipeLimiterPressure = brakePipe.Pressure(); + actFlowSpeed = 0; + } + // the spring brake released by hand, without the command to the other vehicles (SpringBrakeActivate()) + void ReleaseSpringBrake() { brakes.spring.activate = false; } + // the mode of the brake (bom_*: PS/PN/EP/MED) set at the selector + void SetBrakeOperatingMode(int const Mode) { brakes.operatingMode = Mode; } + // the brake cut out or put back by the player, which the AI's wagon inspector no longer puts back on its own + void ClaimBrakeCutOut() { brakes.cutOutByInspector = false; } + // the pressure of the brake pipe of the consist, as the driver's vehicle measures it + void SetEquivalentPipePressure(double const Pressure) { brakes.equivalentPipePressure = Pressure; } + // the inverters of an induction motor drive, switched in and out from the cab + bool InverterActivated(std::size_t const Index) const { return inductionMotor.inverters[Index].Activate; } + void SwitchInverter(std::size_t const Index, bool const State) { inductionMotor.inverters[Index].Activate = State; } + // the distance run, kept between the sessions, and whether a cab shows it + void SetOdometer(odometer::reading const &Reading) { Odometer = Reading; } + void ShowOdometer() { Odometer.shown = true; } bool UniversalResetButton(int const Button, range_t const Notify = range_t::consist); bool RelayReset(int const Relays, range_t const Notify = range_t::consist); // resets specified relays // the drive of the kind of engine of the vehicle (physics/components/drive.h) diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 4566e17f0..5e1f86745 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -1046,6 +1046,8 @@ public: // the blending of the ED and EP brakes of the consist this vehicle leads, with induction motors physics::ConsistBrakeBlending brakeBlending; + // the state of each pantograph the sounds last followed, up or down + ByEnd m_pantographsoundstate{ false, false }; // vehicle shaking calculations // TBD, TODO: make an object out of it diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index 6ced9b912..514bae9f2 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -107,8 +107,7 @@ void TController::Activation() if( occupied->brakes.config.handlePositions > 0 && ( BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic ) ) { - occupied->brakes.pipeLimiterPressure = occupied->brakePipe.Pressure(); - occupied->SetActFlowSpeed(0); + occupied->ResetPipeStabiliser(); } BrakeLevelSet( occupied->brakes.HandlePosition() ); } @@ -170,7 +169,7 @@ void TController::AutoRewident() } // potentially release manual brake d->physics->DecManualBrakeLevel( ManualBrakePosNo ); - d->physics->brakes.spring.activate = false; + d->physics->ReleaseSpringBrake(); } BrakeReinspectionPending = reinspect; //ustawianie trybu pracy zadajnika hamulca, wystarczy raz po inicjalizacji AI @@ -178,7 +177,7 @@ void TController::AutoRewident() // if a human is in charge leave the brake mode up to them, otherwise do as you like for( int i = 1; i <= 8; i *= 2 ) { if( ( occupied->brakes.config.availableOperatingModes & i ) > 0 ) { - occupied->brakes.operatingMode = i; + occupied->SetBrakeOperatingMode(i); } } } diff --git a/vehicle/cab/brakecommands.cpp b/vehicle/cab/brakecommands.cpp index 3d5cb341c..19085f5e5 100644 --- a/vehicle/cab/brakecommands.cpp +++ b/vehicle/cab/brakecommands.cpp @@ -468,7 +468,7 @@ void TTrain::OnCommand_trainbrakeoperationtoggle(TTrain *Train, command_data con vehicle->physics->brakes.distributor->SetBrakeStatus(vehicle->physics->brakes.distributor->GetBrakeStatus() ^ b_dmg); // the brake is the player's now, the wagon inspector won't put it back on its own - vehicle->physics->brakes.cutOutByInspector = false; + vehicle->physics->ClaimBrakeCutOut(); } } diff --git a/vehicle/cab/equipmentcommands.cpp b/vehicle/cab/equipmentcommands.cpp index c1c73a5c7..fb017f240 100644 --- a/vehicle/cab/equipmentcommands.cpp +++ b/vehicle/cab/equipmentcommands.cpp @@ -421,7 +421,7 @@ void TTrain::OnCommand_inverterenable(TTrain *Train, command_data const &Command { if (itemindex < p->physics->inductionMotor.inverterCount) { - p->physics->inductionMotor.inverters[itemindex].Activate = true; + p->physics->SwitchInverter(itemindex, true); break; } else @@ -460,7 +460,7 @@ void TTrain::OnCommand_inverterdisable(TTrain *Train, command_data const &Comman { if (itemindex < p->physics->inductionMotor.inverterCount) { - p->physics->inductionMotor.inverters[itemindex].Activate = false; + p->physics->SwitchInverter(itemindex, false); break; } else @@ -499,7 +499,7 @@ void TTrain::OnCommand_invertertoggle(TTrain *Train, command_data const &Command { if (itemindex < p->physics->inductionMotor.inverterCount) { - p->physics->inductionMotor.inverters[itemindex].Activate = !p->physics->inductionMotor.inverters[itemindex].Activate; + p->physics->SwitchInverter(itemindex, !p->physics->InverterActivated(itemindex)); // visual feedback item.UpdateValue(p->physics->inductionMotor.inverters[itemindex].Activate ? 1.0 : 0.0, Train->dsbSwitch); break; diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index ae1add60b..0f4a65b83 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -552,7 +552,7 @@ bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) DynamicObject->mdKabina->Init(); // obrócenie modelu oraz optymalizacja, również zapisanie binarnego // the vehicle has a cab, a player is in it: the odometer store keeps the vehicle also when its type has no // driver's brake valve (eu07/maszyna#72) - DynamicObject->physics->Odometer.shown = true; + DynamicObject->physics->ShowOdometer(); } set_cab_controls(NewCabNo < 0 ? 2 : NewCabNo); @@ -2006,7 +2006,7 @@ bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int con gauge.AssignDouble(&controlled->Odometer.km); // the vehicle the counter counts for is one the odometer store keeps, also in the sessions the counter seeds // nothing (its state is a saved one by then) and when it's the motor car of the unit the cab is in - controlled->Odometer.shown = true; + controlled->ShowOdometer(); } else if (Label == "shuntmodepower:") { diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index 9fac4a7b1..114c279af 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -237,7 +237,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" // utworzenie parametrów fizyki physics = new physics::Vehicle(iDirection ? fVel : -fVel, Type_Name, asName, Cab); // the vehicle carries on with the odometer state of its earlier sessions (eu07/maszyna#72) - physics->Odometer = odometer::starting_state( odometer::states(), asName, asBaseDir ); + physics->SetOdometer( odometer::starting_state( odometer::states(), asName, asBaseDir ) ); // McZapkie: TypeName musi byc nazwą CHK/MMD pojazdu if (!physics->LoadFIZ(asBaseDir)) { // jak wczytanie CHK się nie uda, to błąd diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 9968a9b35..bfe675a9e 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -302,7 +302,7 @@ void TDynamicObject::updateTractionVoltage( double const dt1 ) void TDynamicObject::updateDriver( double const dt1 ) { if( Mechanik->primary() ) { - physics->brakes.equivalentPipePressure = GetEPP(); // srednie cisnienie w PG + physics->SetEquivalentPipePressure( GetEPP() ); // srednie cisnienie w PG } if (Mechanik->primary() && (physics->EngineType == TEngineType::DieselEngine || @@ -843,7 +843,7 @@ void TDynamicObject::updatePantographMotion( int const i, TAnimPant *p, double c void TDynamicObject::playPantographDropSounds() { // TBD, TODO: generate sound event during physics update instead? - if( physics->pantographs[VehicleEnd::front].sound_event != physics->pantographs[ VehicleEnd::front ].is_active ) { + if( m_pantographsoundstate[ VehicleEnd::front ] != physics->pantographs[ VehicleEnd::front ].is_active ) { if( physics->pantographs[ VehicleEnd::front ].is_active ) { // pantograph moving up // TBD: add a sound? @@ -857,9 +857,9 @@ void TDynamicObject::playPantographDropSounds() } } } - physics->pantographs[ VehicleEnd::front ].sound_event = physics->pantographs[ VehicleEnd::front ].is_active; + m_pantographsoundstate[ VehicleEnd::front ] = physics->pantographs[ VehicleEnd::front ].is_active; } - if( physics->pantographs[ VehicleEnd::rear ].sound_event != physics->pantographs[ VehicleEnd::rear ].is_active ) { + if( m_pantographsoundstate[ VehicleEnd::rear ] != physics->pantographs[ VehicleEnd::rear ].is_active ) { if( physics->pantographs[ VehicleEnd::rear ].is_active ) { // pantograph moving up // TBD: add a sound? @@ -873,7 +873,7 @@ void TDynamicObject::playPantographDropSounds() } } } - physics->pantographs[ VehicleEnd::rear ].sound_event = physics->pantographs[ VehicleEnd::rear ].is_active; + m_pantographsoundstate[ VehicleEnd::rear ] = physics->pantographs[ VehicleEnd::rear ].is_active; } } From 74f0aa240d1554da449d31059b9c87fcd5e28b49 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 13:06:16 +0100 Subject: [PATCH 25/30] refactor(ai): the cab and the whois event are no longer friends of the AI, its public fields are private TTrain and whois_event reached into the private members of TController as its friends; they read what the AI knows of its consist and its route through queries now (ConsistDoorsOpen(), ConsistConverterOverloaded(), ConsistLength(), DesiredVelocity(), NextSignalVelocity(), BrakesReleaseLevel(), ...), and the cab changes the radio channel through SetRadioChannel() rather than a reference to the AI's field. The reversers of the consist, the stations of the timetable and the obstacle ahead are public queries and operations. The public fields of TController are private: whether the AI drives (AIControllFlag()), the masks of the running without current the vehicles of the consist set (MarkOverhead(), the same bits TDynamicObject::OverheadTrack() set itself), the most deceleration of the blended brakes (MedAmax(), SetMedAmax()), and the positions the driving aid panels show. Only the four debug and timetable panels stay friends. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- application/driverhints.cpp | 200 ++++++++++++++--------------- application/driveruipanels.cpp | 2 +- simulation/blackboxrecorder.cpp | 2 +- simulation/simulation.cpp | 2 +- vehicle/Driver.h | 63 +++++++-- vehicle/Train.h | 4 +- vehicle/ai/consist.cpp | 26 ++-- vehicle/ai/controls.cpp | 6 +- vehicle/ai/doors.cpp | 2 +- vehicle/ai/driver.cpp | 12 +- vehicle/ai/engine.cpp | 4 +- vehicle/ai/force.cpp | 6 +- vehicle/ai/orders.cpp | 16 +-- vehicle/ai/routescan.cpp | 4 +- vehicle/ai/situation.cpp | 4 +- vehicle/ai/speed.cpp | 2 +- vehicle/ai/speedtable.cpp | 10 +- vehicle/cab/auxiliarycommands.cpp | 4 +- vehicle/cab/controllercommands.cpp | 2 +- vehicle/cab/setup.cpp | 2 +- vehicle/cab/signalcommands.cpp | 2 +- vehicle/cab/sounds.cpp | 2 +- vehicle/cab/train.cpp | 32 ++--- vehicle/cab/update.cpp | 32 ++--- vehicle/crewchange.cpp | 2 +- vehicle/dynamic/update.cpp | 22 +--- vehicle/dynamic/vehicletable.cpp | 2 +- vehicle/dynamic/visual.cpp | 2 +- world/Event.cpp | 2 +- 29 files changed, 251 insertions(+), 220 deletions(-) diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 7750339f3..13641f60b 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -82,7 +82,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) switch( Action ) { // battery case driver_hint::batteryon: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->BatterySwitch( true ); } remove_hint( driver_hint::batteryoff ); @@ -93,7 +93,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::batteryoff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->BatterySwitch( false ); } remove_hint( driver_hint::batteryon ); @@ -105,7 +105,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // battery case driver_hint::cabactivation: { - if (AIControllFlag && occupied->lowVoltage.Is24vAvailable()) { + if (aiControlled && occupied->lowVoltage.Is24vAvailable()) { occupied->CabActivisation(); CheckVehicles(); } @@ -117,7 +117,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::cabdeactivation: { - if (AIControllFlag) { + if (aiControlled) { occupied->CabDeactivisation(); } remove_hint( driver_hint::cabactivation ); @@ -129,7 +129,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // radio case driver_hint::radioon: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->SetRadio(true); } remove_hint( driver_hint::radiooff ); @@ -140,7 +140,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::radiofuseon: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->SetRadioFuse(true); } hint( @@ -150,7 +150,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::radiochannel: { - if( AIControllFlag ) { + if( aiControlled ) { iRadioChannel = static_cast( Actionparameter ); } hint( @@ -161,7 +161,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::radiooff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->SetRadio(false); } remove_hint( driver_hint::radioon ); @@ -173,7 +173,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // oil pump case driver_hint::oilpumpon: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->OilPumpSwitch( true ); } remove_hint( driver_hint::oilpumpoff ); @@ -185,7 +185,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::oilpumpoff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->OilPumpSwitch( false ); } remove_hint( driver_hint::oilpumpon ); @@ -198,7 +198,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // fuel pump case driver_hint::fuelpumpon: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->FuelPumpSwitch( true ); } remove_hint( driver_hint::fuelpumpoff ); @@ -210,7 +210,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::fuelpumpoff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->FuelPumpSwitch( false ); } remove_hint( driver_hint::fuelpumpon ); @@ -223,7 +223,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // pantographs case driver_hint::pantographairsourcesetmain: { - if( AIControllFlag ) { + if( aiControlled ) { pantographUnit->pantographAir.ConnectToMainReservoir(true); } remove_hint( driver_hint::pantographairsourcesetauxiliary ); @@ -234,7 +234,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::pantographairsourcesetauxiliary: { - if( AIControllFlag ) { + if( aiControlled ) { pantographUnit->pantographAir.ConnectToMainReservoir(false); } remove_hint( driver_hint::pantographcompressoron ); @@ -245,7 +245,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::pantographcompressoron: { - if( AIControllFlag ) { + if( aiControlled ) { pantographUnit->pantographAir.SwitchCompressor(true); } remove_hint( driver_hint::pantographcompressoroff ); @@ -256,7 +256,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::pantographcompressoroff: { - if( AIControllFlag ) { + if( aiControlled ) { pantographUnit->pantographAir.SwitchCompressor(false); } remove_hint( driver_hint::pantographcompressoron ); @@ -267,7 +267,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::pantographsvalveon: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->OperatePantographsValve( operation_t::enable ); } remove_hint( driver_hint::pantographsvalveoff ); @@ -278,7 +278,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::frontpantographvalveon: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->OperatePantographValve( VehicleEnd::front, operation_t::enable ); } remove_hint( driver_hint::frontpantographvalveoff ); @@ -290,7 +290,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::frontpantographvalveoff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->OperatePantographValve( VehicleEnd::front, operation_t::disable ); } remove_hint( driver_hint::frontpantographvalveon ); @@ -301,7 +301,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::rearpantographvalveon: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->OperatePantographValve( VehicleEnd::rear, operation_t::enable ); } remove_hint( driver_hint::rearpantographvalveoff ); @@ -313,7 +313,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::rearpantographvalveoff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->OperatePantographValve( VehicleEnd::rear, operation_t::disable ); } remove_hint( driver_hint::rearpantographvalveon ); @@ -325,7 +325,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // converter case driver_hint::converteron: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->ConverterSwitch( true ); // the local switch of the converter too, where the line contactors wait for the vehicle's own converter // (LineContactorsInterlock): left off by the human driver, that vehicle would never take power @@ -344,7 +344,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::converteroff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->ConverterSwitch( false ); } remove_hint( driver_hint::converteron ); @@ -356,7 +356,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // relays case driver_hint::primaryconverteroverloadreset: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->RelayReset( relay_t::primaryconverteroverload ); } hint( @@ -366,7 +366,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::maincircuitgroundreset: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->RelayReset( relay_t::maincircuitground ); } hint( @@ -376,7 +376,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::tractionnmotoroverloadreset: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->RelayReset( relay_t::tractionnmotoroverload ); } hint( @@ -387,7 +387,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // line breaker case driver_hint::linebreakerclose: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->MainSwitch( true ); } remove_hint( driver_hint::linebreakeropen ); @@ -398,7 +398,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::linebreakeropen: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->MainSwitch( false ); } remove_hint( driver_hint::linebreakerclose ); @@ -411,7 +411,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // compressor case driver_hint::compressoron: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->CompressorSwitch( true ); } remove_hint( driver_hint::compressoroff ); @@ -422,7 +422,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::compressoroff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->CompressorSwitch( false ); } remove_hint( driver_hint::compressoron ); @@ -433,7 +433,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::frontmotorblowerson: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->MotorBlowersSwitchOff( false, VehicleEnd::front ); occupied->MotorBlowersSwitch( true, VehicleEnd::front ); } @@ -446,7 +446,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::rearmotorblowerson: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->MotorBlowersSwitchOff( false, VehicleEnd::rear ); occupied->MotorBlowersSwitch( true, VehicleEnd::rear ); } @@ -460,7 +460,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // spring brake case driver_hint::springbrakeon: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->SpringBrakeActivate( true ); } remove_hint( driver_hint::springbrakeoff ); @@ -471,7 +471,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::springbrakeoff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->SpringBrakeActivate( false ); } remove_hint( driver_hint::springbrakeon ); @@ -483,7 +483,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // manual brake case driver_hint::manualbrakon: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->IncManualBrakeLevel( ManualBrakePosNo ); } remove_hint( driver_hint::manualbrakoff ); @@ -494,7 +494,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::manualbrakoff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->DecManualBrakeLevel( ManualBrakePosNo ); } remove_hint( driver_hint::manualbrakon ); @@ -506,7 +506,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // master controller case driver_hint::mastercontrollersetidle: { - if( AIControllFlag ) { + if( aiControlled ) { while( mvControlling->RList[mvControlling->MainCtrlPos()].Mn == 0 && mvControlling->IncMainCtrl(1) ) { // all work is done in the loop header @@ -520,7 +520,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::mastercontrollersetseriesmode: { - if (AIControllFlag && mvControlling->RList[ mvControlling->MainCtrlPos() ].Bn > 1) { + if (aiControlled && mvControlling->RList[ mvControlling->MainCtrlPos() ].Bn > 1) { // limit yourself to series mode if( mvControlling->ScndCtrlPos() ) { mvControlling->DecScndCtrl( 2 ); @@ -538,7 +538,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::mastercontrollersetzerospeed: { - if( AIControllFlag ) { + if( aiControlled ) { ZeroSpeed(); } remove_master_controller_hints(); @@ -549,7 +549,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::mastercontrollersetreverserunlock: { - if( AIControllFlag ) { + if( aiControlled ) { while( false == mvControlling->EIMDirectionChangeAllow() && mvControlling->DecMainCtrl(1) ) { // all work is done in the loop header @@ -564,7 +564,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::tractiveforcedecrease: { - if( AIControllFlag ) { + if( aiControlled ) { DecSpeed(); } remove_master_controller_hints(); @@ -580,7 +580,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::tractiveforceincrease: { - if( AIControllFlag ) { + if( aiControlled ) { IncSpeed(); } remove_master_controller_hints(); @@ -598,7 +598,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::bufferscompress: { - if (AIControllFlag && std::abs( mvControlling->Ft ) < 50000.0) { + if (aiControlled && std::abs( mvControlling->Ft ) < 50000.0) { IncSpeed(); } remove_master_controller_hints(); @@ -610,7 +610,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::secondcontrollersetzero: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->DecScndCtrl( 2 ); } remove_master_controller_hints(); @@ -622,7 +622,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::waterpumpon: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterPumpSwitch( true ); } remove_hint( driver_hint::waterpumpoff ); @@ -634,7 +634,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::waterpumpoff: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterPumpSwitch( false ); } remove_hint( driver_hint::waterpumpon ); @@ -646,7 +646,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::waterpumpbreakeron: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterPumpBreakerSwitch( true ); } remove_hint( driver_hint::waterpumpbreakeroff ); @@ -658,7 +658,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::waterpumpbreakeroff: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterPumpBreakerSwitch( false ); } remove_hint( driver_hint::waterpumpbreakeron ); @@ -670,7 +670,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::waterheateron: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterHeaterSwitch( true ); } remove_hint( driver_hint::waterheateroff ); @@ -682,7 +682,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::waterheateroff: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterHeaterSwitch( false ); } remove_hint( driver_hint::waterheateron ); @@ -694,7 +694,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::waterheaterbreakeron: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterHeaterBreakerSwitch( true ); } remove_hint( driver_hint::waterheaterbreakeroff ); @@ -706,7 +706,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::waterheaterbreakeroff: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterHeaterBreakerSwitch( false ); } remove_hint( driver_hint::waterheaterbreakeron ); @@ -718,7 +718,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::watercircuitslinkon: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterCircuitsLinkSwitch( true ); } remove_hint( driver_hint::watercircuitslinkoff ); @@ -729,7 +729,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::watercircuitslinkoff: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterCircuitsLinkSwitch( false ); } remove_hint( driver_hint::watercircuitslinkon ); @@ -796,7 +796,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // driver_hint_brakingforcesetzero // driver_hint_brakingforcelap case driver_hint::trainbrakesetpipeunlock: { - if (AIControllFlag && occupied->brakes.pipeLock.unlockHandlePosition != -3) { + if (aiControlled && occupied->brakes.pipeLock.unlockHandlePosition != -3) { while( BrakeCtrlPosition >= occupied->brakes.pipeLock.unlockHandlePosition && BrakeLevelAdd(-1) ) { // all work is done in the header @@ -810,7 +810,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::trainbrakerelease: { - if( AIControllFlag ) { + if( aiControlled ) { // occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_RP ) ); BrakeLevelSet( gbh_RP ); } @@ -823,7 +823,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::trainbrakeapply: { - if( AIControllFlag ) { + if( aiControlled ) { // za radą yB ustawiamy pozycję 3 kranu (ruszanie kranem w innych miejscach powino zostać wyłączone) if( BrakeSystem == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ) { occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_EPB ) ); @@ -840,7 +840,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::brakingforcedecrease: { - if( AIControllFlag ) { + if( aiControlled ) { auto const brakingcontrolschange { DecBrake() }; // set optional delay between brake adjustments if( brakingcontrolschange && Actionparameter > 0 ) { @@ -856,7 +856,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::brakingforceincrease: { - if( AIControllFlag ) { + if( aiControlled ) { auto const brakingcontrolschange { IncBrake() }; // set optional delay between brake adjustments if( brakingcontrolschange && Actionparameter > 0 ) { @@ -876,7 +876,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::brakingforcesetzero: { // releases both train and independent brake - if( AIControllFlag ) { + if( aiControlled ) { while( true == DecBrake() ) { // all work is done in the loop condition } @@ -889,7 +889,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::brakingforcelap: { - if( AIControllFlag ) { + if( aiControlled ) { LapBrake(); } remove_train_brake_hints(); @@ -899,7 +899,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // independent brake case driver_hint::independentbrakeapply: { - if (AIControllFlag && occupied->brakes.IndependentPosition() < 1.0) { + if (aiControlled && occupied->brakes.IndependentPosition() < 1.0) { occupied->IncLocalBrakeLevel( LocalBrakePosNo ); if (occupied->EIMCtrlEmergency) { occupied->DecLocalBrakeLevel(1); @@ -914,7 +914,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::independentbrakerelease: { - if( AIControllFlag ) { + if( aiControlled ) { ZeroLocalBrake(); } remove_hint( driver_hint::independentbrakeapply ); @@ -926,7 +926,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // reverser case driver_hint::directionforward: { - if( AIControllFlag ) { + if( aiControlled ) { OrderDirectionChange( 1, occupied ); } remove_reverser_hints(); @@ -937,7 +937,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::directionbackward: { - if( AIControllFlag ) { + if( aiControlled ) { OrderDirectionChange( -1, occupied ); } remove_reverser_hints(); @@ -948,7 +948,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::directionother: { - if( AIControllFlag ) { + if( aiControlled ) { // DirectionForward( occupied->DirAbsolute < 0 ); OrderDirectionChange( iDirectionOrder, occupied ); DirectionChange(); @@ -961,7 +961,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::directionnone: { - if( AIControllFlag ) { + if( aiControlled ) { ZeroDirection(); } remove_reverser_hints(); @@ -973,7 +973,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // anti-slip systems case driver_hint::sandingon: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->Sandbox( true ); } remove_hint( driver_hint::sandingoff ); @@ -984,7 +984,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::sandingoff: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->Sandbox( false ); } remove_hint( driver_hint::sandingon ); @@ -995,7 +995,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::antislip: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->AntiSlippingButton(); } hint( @@ -1006,7 +1006,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // horns case driver_hint::hornon: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->SetWarningSignal(static_cast( Actionparameter )); } remove_hint( driver_hint::hornoff ); @@ -1018,7 +1018,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::hornoff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->SetWarningSignal(0); } /* @@ -1033,7 +1033,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // door locks case driver_hint::consistdoorlockson: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->LockDoors( true ); } // TODO: remove other door lock hints @@ -1045,7 +1045,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // departure signal case driver_hint::departuresignalon: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->signal_departure( true ); } remove_hint( driver_hint::departuresignaloff ); @@ -1056,7 +1056,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::departuresignaloff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->signal_departure( false ); } remove_hint( driver_hint::departuresignalon ); @@ -1068,7 +1068,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // consist doors case driver_hint::doorrightopen: { - if( AIControllFlag + if( aiControlled || pVehicle->physics->Doors.open_control == control_t::conductor ) { pVehicle->physics->OperateDoors( VehicleSide::right, true ); } @@ -1080,7 +1080,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::doorrightclose: { - if( AIControllFlag + if( aiControlled || pVehicle->physics->Doors.open_control == control_t::conductor ) { pVehicle->physics->OperateDoors( VehicleSide::right, false ); } @@ -1092,7 +1092,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::doorleftopen: { - if( AIControllFlag + if( aiControlled || pVehicle->physics->Doors.open_control == control_t::conductor ) { pVehicle->physics->OperateDoors( VehicleSide::left, true ); } @@ -1104,7 +1104,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::doorleftclose: { - if( AIControllFlag + if( aiControlled || pVehicle->physics->Doors.open_control == control_t::conductor ) { pVehicle->physics->OperateDoors( VehicleSide::left, false ); } @@ -1116,7 +1116,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::doorrightpermiton: { - if( AIControllFlag ) { + if( aiControlled ) { pVehicle->physics->PermitDoors( VehicleSide::right, true ); } remove_hint( driver_hint::doorrightpermitoff ); @@ -1127,7 +1127,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::doorrightpermitoff: { - if( AIControllFlag ) { + if( aiControlled ) { pVehicle->physics->PermitDoors( VehicleSide::right, false ); } remove_hint( driver_hint::doorrightpermiton ); @@ -1138,7 +1138,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::doorleftpermiton: { - if( AIControllFlag ) { + if( aiControlled ) { pVehicle->physics->PermitDoors( VehicleSide::left, true ); } remove_hint( driver_hint::doorleftpermitoff ); @@ -1149,7 +1149,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::doorleftpermitoff: { - if( AIControllFlag ) { + if( aiControlled ) { pVehicle->physics->PermitDoors( VehicleSide::left, false ); } remove_hint( driver_hint::doorleftpermiton ); @@ -1161,7 +1161,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // doorsteps, as the timetable asks (eu07/maszyna#95) case driver_hint::doorstepon: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->PermitDoorStep( true ); } remove_hint( driver_hint::doorstepoff ); @@ -1172,7 +1172,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::doorstepoff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->PermitDoorStep( false ); } remove_hint( driver_hint::doorstepon ); @@ -1184,7 +1184,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // consist lights case driver_hint::consistlightson: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->CompartmentLightsSwitch( true ); occupied->CompartmentLightsSwitchOff( false ); } @@ -1197,7 +1197,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::consistlightsoff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->CompartmentLightsSwitch( false ); occupied->CompartmentLightsSwitchOff( true ); } @@ -1211,7 +1211,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // consist heating case driver_hint::consistheatingon: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->HeatingSwitch( true ); } remove_hint( driver_hint::consistheatingoff ); @@ -1222,7 +1222,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::consistheatingoff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->HeatingSwitch( false ); } remove_hint( driver_hint::consistheatingon ); @@ -1234,7 +1234,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::securitysystemreset: { - if (AIControllFlag && occupied->SecuritySystem.is_blinking()) + if (aiControlled && occupied->SecuritySystem.is_blinking()) occupied->SecuritySystemReset(); hint( Action, @@ -1243,7 +1243,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::shpsystemreset: { - if (AIControllFlag && occupied->SecuritySystem.is_cabsignal_blinking()) + if (aiControlled && occupied->SecuritySystem.is_cabsignal_blinking()) occupied->SecuritySystem.cabsignal_reset(); hint( Action, @@ -1253,7 +1253,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::couplingadapterattach: { // TODO: run also for potential settings-based virtual assistant - if( AIControllFlag ) { + if( aiControlled ) { pVehicles[ VehicleEnd::front ]->attach_coupler_adapter( EndOf( static_cast(Actionparameter) ) ); } hint( @@ -1264,7 +1264,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::couplingadapterremove: { - if( AIControllFlag || Global.AITrainman ) { + if( aiControlled || Global.AITrainman ) { pVehicles[ VehicleEnd::front ]->remove_coupler_adapter( EndOf( static_cast(Actionparameter) ) ); } hint( @@ -1276,7 +1276,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // lights case driver_hint::headcodepc1: { - if( AIControllFlag ) { + if( aiControlled ) { pVehicles[ VehicleEnd::front ]->RaLightsSet( light::headlight_left | light::headlight_right | light::headlight_upper, -1 ); } remove_hint( driver_hint::headcodepc2 ); @@ -1289,7 +1289,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::headcodepc2: { - if( AIControllFlag ) { + if( aiControlled ) { pVehicles[ VehicleEnd::front ]->RaLightsSet( light::redmarker_left | light::headlight_right | light::headlight_upper, -1 ); } remove_hint( driver_hint::headcodepc1 ); @@ -1304,7 +1304,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) case driver_hint::headcodetb1: { // HACK: the 'front' and 'rear' of the consist is determined by current consist direction // since direction shouldn't affect Tb1 light configuration, we 'counter' this behaviour by virtually swapping end vehicles - if( AIControllFlag ) { + if( aiControlled ) { if( occupied->DirActive >= 0 ) { Lights( light::headlight_right, light::headlight_left ); } else { Lights( light::headlight_left, light::headlight_right ); } } @@ -1321,7 +1321,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::headcodepc5: { - if( AIControllFlag + if( aiControlled || ( Global.AITrainman && false == pVehicles[VehicleEnd::rear]->is_connected(pVehicle, Coupling::control) ) ) { pVehicles[ VehicleEnd::rear ]->RaLightsSet( -1, light::redmarker_left | light::redmarker_right | light::rearendsignals ); } @@ -1334,7 +1334,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::lightsoff: { - if( AIControllFlag ) { + if( aiControlled ) { Lights( 0, 0 ); } remove_hint( driver_hint::headcodepc1 ); @@ -1351,7 +1351,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // releaser case driver_hint::releaseron: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->BrakeReleaser( 1 ); } remove_hint( driver_hint::releaseroff ); @@ -1362,7 +1362,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::releaseroff: { - if( AIControllFlag ) { + if( aiControlled ) { occupied->BrakeReleaser( 0 ); } remove_hint( driver_hint::releaseron ); diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 81bc2bdf9..1a3963434 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -222,7 +222,7 @@ drivingaid_panel::render_contents() { auto const *driver = (simulation::Train && simulation::Train->Dynamic()) ? simulation::Train->Dynamic()->Mechanik : nullptr; if (driver && (false == Global.RealisticControlMode || DebugModeFlag)) { - bool autopilot = driver->AIControllFlag; + bool autopilot = driver->AIControllFlag(); if (ImGui::Checkbox(STR_C("autopilot"), &autopilot)) { command_relay commandrelay; commandrelay.post(autopilot ? user_command::aidriverenable : user_command::aidriverdisable, 0.0, 0.0, GLFW_PRESS, 0); diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 24db6b236..48749f3ff 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -66,7 +66,7 @@ std::string text_of(std::string_view const Win1250) { blackbox::driver driver_of(TDynamicObject const &Vehicle) { if (Vehicle.Mechanik == nullptr) return blackbox::driver::none; - return Vehicle.Mechanik->AIControllFlag ? blackbox::driver::ai : blackbox::driver::human; + return Vehicle.Mechanik->AIControllFlag() ? blackbox::driver::ai : blackbox::driver::human; } // the switches of the user's train: those of its own vehicle, and those of the one with the motors it drives diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 8c2e9f0d3..a63ddfc03 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -312,7 +312,7 @@ void state_manager::process_commands() { targetvehicle->ctOwner == currentvehicle->Mechanik || targetvehicle->ctOwner == currentvehicle->ctOwner }; auto const isincharge{ currentvehicle->Mechanik->primary() }; - auto const aidriveractive{ currentvehicle->Mechanik->AIControllFlag }; + auto const aidriveractive{ currentvehicle->Mechanik->AIControllFlag() }; // TODO: support for primary mode request passed as commanddata.param1 if( !sameconsist && isincharge ) { // oddajemy dotychczasowy AI diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 9ed95141f..c58ce134b 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -254,12 +254,10 @@ struct SandedStart class TController { // TBD: few authorized inspectors, or bunch of public getters? - friend class TTrain; friend class drivingaid_panel; friend class timetable_panel; friend class scenario_panel; friend class debug_panel; - friend class whois_event; public: TController( bool AI, TDynamicObject *NewControll, bool InitPsyche, bool primary = true ); @@ -316,6 +314,36 @@ public: int light_hint( VehicleEnd const End ) const { return m_lighthints[ End ]; } // the order the driver goes by now: a train run, shunting and the like DriverOrders order_current() const { return OrderCurrentGet(); } + // the reversers of the consist set as the driver's one, where they went apart + void sync_consist_reversers(); + // the stations of the timetable: where the train is among them, how many there are, whether it stops at the next + int StationIndex() const; + int StationCount() const; + bool IsStop() const; + // what the cab shows of the consist the driver leads + BySide const &ConsistDoorsOpen() const { return IsAnyDoorOpen; } + BySide const &ConsistDoorsOnlyOpen() const { return IsAnyDoorOnlyOpen; } // the steps not counted + BySide const &ConsistDoorPermits() const { return IsAnyDoorPermitActive; } + door_closure_t ConsistDoorClosure() const { return DoorClosure; } + bool ConsistConverterOverloaded() const { return IsAnyConverterOverloadRelayOpen; } + bool ConsistCompressorEnabled() const { return IsAnyCompressorEnabled; } + double ConsistLength() const { return fLength; } + int RadioChannel() const { return iRadioChannel; } + void SetRadioChannel( int const Channel ) { iRadioChannel = Channel; } + int Helper() const { return HelperState; } + // what the driver goes by on the route, for the screens of the cab and the events + double DesiredVelocity() const { return VelDesired; } + double RoadVelocity() const { return VelRoad; } + double LastLimitVelocity() const { return VelLimitLast; } + double LastSignalVelocity() const { return VelSignalLast; } + double NextSignalVelocity() const { return VelSignalNext; } + double NextVelocity() const { return VelNext; } + double ProximityDistance() const { return ActualProximityDist; } + bool AtPassengerStop() const { return IsAtPassengerStop; } + // how far the brakes of the consist are released (fReady), the most braked vehicle counting + double BrakesReleaseLevel() const { return fReady; } + // the distance to the obstacle ahead on the track + double TrackObstacle() const; private: // tells the black box of the train at the station of its timetable it makes for, at the stop point given void record_station( TSpeedPos const &Point, std::uint8_t Kind ) const; @@ -349,7 +377,6 @@ private: void DirectionForward( bool forward ); void ZeroDirection(); int OrderDirectionChange( int newdir, physics::Vehicle *Vehicle ); - void sync_consist_reversers(); void Lights( int head, int rear ); std::string StopReasonText() const; double BrakeAccFactor() const; @@ -446,7 +473,30 @@ private: void cue_action( driver_hint const Action, float const Actionparameter = 0.f ); // members public: - bool AIControllFlag = false; // rzeczywisty/wirtualny maszynista + // the AI drives, or a human does + bool AIControllFlag() const { return aiControlled; } + // what the overhead line of the track under a vehicle of the consist asks for (TDynamicObject::OverheadTrack()), by the + // bit of that vehicle: below zero the usual running, above it running without current with the pantographs down, zero + // running without current with them up + void MarkOverhead( int const Mask, float const Mode ) { + if( Mode < 0.0 ) { // normalna jazda po tym torze + iOverheadZero &= ~Mask; // zerowanie bitu - może pobierać prąd + iOverheadDown &= ~Mask; // zerowanie bitu - może podnieść pantograf + } + else if( Mode > 0.0 ) { // opuszczenie pantografów + iOverheadZero |= Mask; // ustawienie bitu - ma jechać bez pobierania prądu + iOverheadDown |= Mask; // ustawienie bitu - ma opuścić pantograf + } + else { // jazda bezprądowa z podniesionym pantografem + iOverheadZero |= Mask; // ustawienie bitu - ma jechać bez pobierania prądu + iOverheadDown &= ~Mask; // zerowanie bitu - może podnieść pantograf + } + } + // the most deceleration of the service braking of the consist with the blended brakes, which the driver goes by + double MedAmax() const { return fMedAmax; } + void SetMedAmax( double const Deceleration ) { fMedAmax = Deceleration; } +private: + bool aiControlled = false; // rzeczywisty/wirtualny maszynista int iOverheadZero = 0; // suma bitowa jezdy bezprądowej, bity ustawiane przez pojazdy z podniesionymi pantografami int iOverheadDown = 0; // suma bitowa opuszczenia pantografów, bity ustawiane przez pojazdy z podniesionymi pantografami double BrakeCtrlPosition = 0.0; // intermediate position of main brake controller @@ -624,8 +674,6 @@ private: bool point_limit_latched( basic_event const *Cell ) const; // how far before a point limit the speed is held down to it double point_limit_approach() const; - // returns most recently calculated distance to potential obstacle ahead - double TrackObstacle() const; void TablePurger(); void TableSort(); inline double MoveDistanceGet() const { @@ -685,9 +733,6 @@ public: Mtable::TTrainParameters const & TrainTimetable() const; private: std::string Relation() const; - int StationIndex() const; - int StationCount() const; - bool IsStop() const; std::string NextStop() const; // tests whether the train is delayed and sets accordingly a driving flag void UpdateDelayFlag(); diff --git a/vehicle/Train.h b/vehicle/Train.h index 89892b423..e77e8ffc4 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -1043,8 +1043,8 @@ private: // plays provided sound from position of the radio bool radio_message_played; void radio_message( sound_source *Message, int const Channel ); - inline auto RadioChannel() const { return Dynamic()->Mechanik ? Dynamic()->Mechanik->iRadioChannel : 1; } - inline auto &RadioChannel() { return Dynamic()->Mechanik->iRadioChannel; } + inline auto RadioChannel() const { return Dynamic()->Mechanik ? Dynamic()->Mechanik->RadioChannel() : 1; } + inline void SetRadioChannel( int const Channel ) { Dynamic()->Mechanik->SetRadioChannel( Channel ); } inline TDynamicObject *Dynamic() { return DynamicObject; }; inline TDynamicObject const *Dynamic() const { return DynamicObject; }; inline physics::Vehicle *Controlled() { return controlled; }; diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index 514bae9f2..1de5dc1af 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -158,7 +158,7 @@ void TController::AutoRewident() // 3. Nastawianie auto setting{settings.begin()}; for (auto *d = pVehicles[0]; d != nullptr && setting != settings.end(); d = d->Next(), ++setting) { - if (false == AIControllFlag && d == pVehicle) { + if (false == aiControlled && d == pVehicle) { // don't touch human-controlled vehicle, but others are free game continue; } @@ -173,7 +173,7 @@ void TController::AutoRewident() } BrakeReinspectionPending = reinspect; //ustawianie trybu pracy zadajnika hamulca, wystarczy raz po inicjalizacji AI - if( true == AIControllFlag ) { + if( true == aiControlled ) { // if a human is in charge leave the brake mode up to them, otherwise do as you like for( int i = 1; i <= 8; i *= 2 ) { if( ( occupied->brakes.config.availableOperatingModes & i ) > 0 ) { @@ -202,7 +202,7 @@ void TController::AutoRewident() BrakeSystem = consist_brake_system(); // Change the EP fuse state only when AI is in charge, don't fiddle with controls when the user is controlling the vehicle - if (AIControllFlag) { + if (aiControlled) { occupied->EpFuseSwitch(BrakeSystem == TBrakeSystem::ElectroPneumatic); } @@ -394,7 +394,7 @@ bool TController::CheckVehicles(DriverOrders user) if( p->asDestination == "none" ) { p->DestinationSet( TrainParams.Relation2, TrainParams.TrainName ); // relacja docelowa, jeśli nie było } - if( AIControllFlag ) { // jeśli prowadzi komputer + if( aiControlled ) { // jeśli prowadzi komputer p->RaLightsSet( 0, 0 ); // gasimy światła } p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła) @@ -450,7 +450,7 @@ bool TController::CheckVehicles(DriverOrders user) // potentially adjust light state control_lights(); // custom ai action for disconnect mode: switch off lights on disconnected vehicle(s) - if( is_train() && true == OrderCurrentGet().HasAll(DriverOrder::disconnect) && AIControllFlag ) { + if( is_train() && true == OrderCurrentGet().HasAll(DriverOrder::disconnect) && aiControlled ) { // światła manewrowe (Tb1) tylko z przodu, aby nie pozostawić odczepionego ze światłem if (occupied->DirActive >= 0) { // jak ma kierunek do przodu @@ -626,7 +626,7 @@ void TController::MoveTo(TDynamicObject *to) if( to->Mechanik != nullptr && to->Mechanik != this ) { // ai controller thunderdome, there can be only one - if( to->Mechanik->AIControllFlag ) { + if( to->Mechanik->aiControlled ) { if( to->Mechanik->primary() ) { // take over boss duties primary( true ); @@ -635,7 +635,7 @@ void TController::MoveTo(TDynamicObject *to) } else { // can't quite delete a human - if( AIControllFlag ) { + if( aiControlled ) { delete this; } return; @@ -741,7 +741,7 @@ TController::determine_consist_state() { } if( wasready ) { // Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka... - if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && occupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy + if( bp >= 0.4 && (aiControlled || Global.AITrainman && occupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy && false == TestFlag(vehicle->brakes.distributor->GetBrakeStatus(), b_dmg) // brake isn't broken && vehicle->brakePipe.Pressure() - occupied->brakes.driverValve->GetRP() > -0.1 // jeśli ciśnienie jak dla jazdy && vehicle->brakes.distributor->GetCRP() > vehicle->brakePipe.Pressure() + 0.12 ) { // wg UIC określone sztywno na 0.04 @@ -749,7 +749,7 @@ TController::determine_consist_state() { // indywidualne luzowanko vehicle->BrakeReleaser(1); } - if (bp < 0.1 && (AIControllFlag || Global.AITrainman) && false == TestFlag(vehicle->brakes.distributor->GetBrakeStatus(), b_dmg) // brake isn't broken + if (bp < 0.1 && (aiControlled || Global.AITrainman) && false == TestFlag(vehicle->brakes.distributor->GetBrakeStatus(), b_dmg) // brake isn't broken && vehicle->brakes.distributor->GetCRP() < vehicle->brakePipe.Pressure() - 0.1) { // już nie jest za dużo w zbiorniku // koniec indywidualnego luzowanka @@ -885,7 +885,7 @@ TController::determine_consist_state() { BrakeCharge.going = false; } auto const trainbrakeapplied { - AIControllFlag ? + aiControlled ? BrakeCtrlPosition > 0.0 : // a human driver's handle, which BrakeCtrlPosition doesn't follow occupied->brakes.HandlePositionSmooth() > occupied->brakes.driverValve->GetPos( bh_RP ) + 0.2 }; @@ -915,13 +915,13 @@ TController::determine_consist_state() { IsConsistCharged = true; BrakeCharge = {}; } - if( AIControllFlag + if( aiControlled && ( false == IsConsistCharged ) && ( false == heldforstart ) ) { Ready = false; } auto const departblocked { - AIControllFlag + aiControlled && occupied->Vel < EU07_AI_NOMOVEMENT && VelDesired > 0.0 && ( false == Ready || fReady > 0.4 ) }; @@ -954,5 +954,5 @@ TController::determine_consist_state() { && ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled ) && ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled ) // the ai goes back to preparing the engine and switches that converter on, the human driver may run with it off - && ( false == AIControllFlag || false == islocalconverterswitchoff ); + && ( false == aiControlled || false == islocalconverterswitchoff ); } diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index 919d77743..e8cacff77 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -906,7 +906,7 @@ bool TController::BrakeLevelAdd(double b) // ma dokręcać do bezoporowych i zdejmować pozycje w przypadku przekroczenia prądu void TController::SpeedSet() { - if( false == AIControllFlag ) { return; } + if( false == aiControlled ) { return; } switch (occupied->EngineType) { @@ -1115,7 +1115,7 @@ void TController::SpeedCntrl(double DesiredSpeed) void TController::SetTimeControllers() { // TBD, TODO: rework this method to use hint system and regardless of driver type - if( false == AIControllFlag || 0 == occupied->CabActive ) { return; } + if( false == aiControlled || 0 == occupied->CabActive ) { return; } //1. Check the type of Main Brake Handle if( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) @@ -1329,7 +1329,7 @@ void TController::SetTimeControllers() void TController::CheckTimeControllers() { // TODO: rework this method to use hint system and regardless of driver type - if( false == AIControllFlag || 0 == mvControlling->CabActive ) { return; } + if( false == aiControlled || 0 == mvControlling->CabActive ) { return; } //1. Check the type of Main Brake Handle if( BrakeSystem == TBrakeSystem::ElectroPneumatic && occupied->brakes.driverValve->TimeEP && !ForcePNBrake ) diff --git a/vehicle/ai/doors.cpp b/vehicle/ai/doors.cpp index 3a3aa7eef..bea5b6d07 100644 --- a/vehicle/ai/doors.cpp +++ b/vehicle/ai/doors.cpp @@ -186,7 +186,7 @@ TController::control_doors() { // HACK: crude way to deal with automatic door opening on W4 preventing further ride // for human-controlled vehicles with no door control and dynamic brake auto-activating with door open // TODO: check if this situation still happens and the hack is still needed - if( false == AIControllFlag && (mvControlling->EngineType == TEngineType::DieselEngine ? mvControlling->RList[mvControlling->MainCtrlPos()].Mn > 0 : mvControlling->MainCtrlPowerPos() > 0) ) { + if( false == aiControlled && (mvControlling->EngineType == TEngineType::DieselEngine ? mvControlling->RList[mvControlling->MainCtrlPos()].Mn > 0 : mvControlling->MainCtrlPowerPos() > 0) ) { // for diesel engines react when engine is put past idle revolutions // for others straightforward master controller check Doors(false); diff --git a/vehicle/ai/driver.cpp b/vehicle/ai/driver.cpp index 57efaa96f..5c5d33bf7 100644 --- a/vehicle/ai/driver.cpp +++ b/vehicle/ai/driver.cpp @@ -55,7 +55,7 @@ bool WriteLogFlag = false; //--------------------------------------------------------------------------- TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, bool Primary) :// czy ma aktywnie prowadzić? - AIControllFlag( AI ), pVehicle( NewControll ) + aiControlled( AI ), pVehicle( NewControll ) { if( pVehicle != nullptr ) { pVehicles[ VehicleEnd::front ] = pVehicle->GetFirstDynamic( VehicleEnd::front ); // pierwszy w kierunku jazdy (Np. Pc1) @@ -388,15 +388,15 @@ TController::Update( double const Timedelta ) { void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck ) { // przejęcie kontroli przez AI albo oddanie - if (AIControllFlag == Aidriver && !Forcevehiclecheck) + if (aiControlled == Aidriver && !Forcevehiclecheck) return; // już jest jak ma być - if( AIControllFlag != Aidriver ) { + if( aiControlled != Aidriver ) { // the autopilot switched on or off simulation::Blackbox.driver_changed( pVehicle, Aidriver ); } if (Aidriver) //żeby nie wykonywać dwa razy { // teraz AI prowadzi - AIControllFlag = AIdriver; + aiControlled = AIdriver; pVehicle->Controller = AIdriver; // the AI doesn't operate the headlight dimmer, drop the state left by the human driver // so the lights set by the AI aren't hidden (dimmer in off position) or dimmed @@ -443,7 +443,7 @@ void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck { // a teraz użytkownik if (eAction == TAction::actSleep || OrderCurrentGet() == DriverOrder::waitForOrders) // gasimy swiatla jesli przejmujemy odstawione pVehicle->RaLightsSet(0, 0); - auto const aiwasdriving { AIControllFlag == AIdriver }; + auto const aiwasdriving { aiControlled == AIdriver }; if( aiwasdriving ) { // the horn, sandbox, departure signal and brake releaser the AI may have latched are momentary for the human driver handover::release_ai_controls( *occupied, *mvControlling ); @@ -452,7 +452,7 @@ void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck // the AI sets the lights directly, leave the selector in matching position so it doesn't revert them later sync_lights_selector(); } - AIControllFlag = Humandriver; + aiControlled = Humandriver; pVehicle->Controller = Humandriver; if( aiwasdriving ) { // same with the headlight dimmer, which is only applied for the human driver diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp index c49ef577d..25fff0e9b 100644 --- a/vehicle/ai/engine.cpp +++ b/vehicle/ai/engine.cpp @@ -252,7 +252,7 @@ TController::report_power_stall( bool const Poweravailable, double const Pantogr } } // 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 ) }; + if( auto const stall { m_powerstall.update( aiControlled ? ai_power::check( state ) : ai_power::stall::waiting, ElapsedTime ) }; stall.has_value() ) { ErrorLog( ai_power::message( *stall, pVehicle->asName, pVehicle->GetPosition() ), logtype::traction ); } @@ -264,7 +264,7 @@ bool TController::ReleaseEngine() { if( occupied->Vel > 0.01 ) { VelDesired = 0.0; AccDesired = std::min( AccDesired, -1.25 ); // hamuj solidnie - if( true == AIControllFlag ) { + if( true == aiControlled ) { // TBD, TODO: make a dedicated braking procedure out of it for potential reuse ZeroSpeed(); IncBrake(); diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp index 70fdb5a36..338e8a0d6 100644 --- a/vehicle/ai/force.cpp +++ b/vehicle/ai/force.cpp @@ -105,7 +105,7 @@ TController::control_tractive_and_braking_force() { // 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 + if( aiControlled && mvControlling->EngineType == TEngineType::DieselElectric && fieldshunting::has_switch( mvControlling->AutoRelayType, mvControlling->FieldShuntSwitch ) && false == mvControlling->AutoRelayFlag ) { @@ -329,7 +329,7 @@ void TController::secure_standing_train() { // 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 + if( aiControlled && ( ( BrakeCtrlPosition < 1.0 ) || ( BrakeCtrlPosition > uphill_start::top_up_position ) ) ) { BrakeLevelSet( 1.0 ); } @@ -518,7 +518,7 @@ void TController::control_braking_force() { && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != DriverOrder::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 + && ( aiControlled || ( false == brake_charge::release_waits( IsConsistCharged, occupied->Vel < EU07_AI_NOMOVEMENT, diff --git a/vehicle/ai/orders.cpp b/vehicle/ai/orders.cpp index 8f8160dd6..d39ae8e69 100644 --- a/vehicle/ai/orders.cpp +++ b/vehicle/ai/orders.cpp @@ -221,7 +221,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N else { // inicjacja pierwszego przystanku i pobranie jego nazwy // HACK: clear the potentially set door state flag to ensure door get opened if applicable - if( true == AIControllFlag ) { + if( true == aiControlled ) { // simplified door closing procedure, to sync actual door state with the door state flag // NOTE: this may result in visually ugly quick switch between closing and opening the doors, but eh if( pVehicle->physics->Doors.close_control == control_t::driver @@ -293,7 +293,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N if (NewValue1<0) //dla ujemnej prędkości iDirectionOrder=-iDirectionOrder; //ma jechać w drugą stronę */ - if (AIControllFlag) // jeśli prowadzi komputer + if (aiControlled) // jeśli prowadzi komputer Activation(); // umieszczenie obsługi we właściwym członie, ustawienie nawrotnika w // przód } @@ -582,7 +582,7 @@ bool TController::PutCommand( std::string NewCommand, double NewValue1, double N // wybór kanału radiowego (którego powinien używać AI, ręczny maszynista musi go ustawić sam) if (NewValue1 >= 0) { // wartości ujemne są zarezerwowane, -1 = nie zmieniać kanału - if( AIControllFlag ) { + if( aiControlled ) { iRadioChannel = NewValue1; } if( iGuardRadio ) { @@ -881,7 +881,7 @@ TController::UpdateChangeDirection() { // TODO: rework into driver mode independent routine if( false == OrderCurrentGet().HasAll(DriverOrder::changeDirection) ) { return; } - if( true == AIControllFlag && occupied->Vel < EU07_AI_NOMOVEMENT ) { + if( true == aiControlled && occupied->Vel < EU07_AI_NOMOVEMENT ) { // sprobuj zmienic kierunek (może być zmieszane z jeszcze jakąś komendą) // jeśli się zatrzymał, to zmieniamy kierunek jazdy, a nawet kabinę/człon Activation(); // ustawienie zadanego wcześniej kierunku i ewentualne przemieszczenie AI @@ -910,7 +910,7 @@ void TController::UpdateLooseShunt() { // when loose shunting try to detect situations where engaged brakes in a consist to be pushed prevent movement // TODO: run also for potential settings-based virtual assistant - auto const autobrakerelease { ( true == AIControllFlag ) }; + auto const autobrakerelease { ( true == aiControlled ) }; if( autobrakerelease && Obstacle.distance < 1.0 @@ -1002,7 +1002,7 @@ TController::UpdateConnect() { } } // próba podczepienia - if ((AIControllFlag || Global.AITrainman) && coupleriscompatible && neighbour.distance < 2) + if ((aiControlled || Global.AITrainman) && coupleriscompatible && neighbour.distance < 2) { vehicleparameters->Attach(couplingend, neighbour.vehicle_end, neighbour.vehicle->physics, iCoupler); } @@ -1058,7 +1058,7 @@ TController::UpdateDisconnect() { if( iVehicleCount >= 0 ) { // early test for human drivers, who might disregard the proper procedure, or perform it before they receive the order to - if( false == AIControllFlag && unit_count(iVehicleCount + 2) <= iVehicleCount + 1 ) { + if( false == aiControlled && unit_count(iVehicleCount + 2) <= iVehicleCount + 1 ) { // iVehicleCount = 0 means the consist should be reduced to (1) leading unit, thus we increase our test values by 1 iVehicleCount = -2; // odczepiono, co było do odczepienia return; // we'll wrap up the procedure on the next update beat @@ -1106,7 +1106,7 @@ TController::UpdateDisconnect() { iVehicleCount = -2; // odczepiono, co było do odczepienia } else { - if( AIControllFlag || Global.AITrainman ) { + if( aiControlled || Global.AITrainman ) { decoupledvehicle->Dettach( decoupledend ); } // tylko jeśli odepnie diff --git a/vehicle/ai/routescan.cpp b/vehicle/ai/routescan.cpp index 8974dd42d..8c9b2f3ec 100644 --- a/vehicle/ai/routescan.cpp +++ b/vehicle/ai/routescan.cpp @@ -339,7 +339,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) /* // NOTE: manual selection disabled due to multiplayer int routewanted; - if( false == AIControllFlag ) { + if( false == aiControlled ) { routewanted = ( input::keys[ GLFW_KEY_LEFT ] != GLFW_RELEASE ? 1 : input::keys[ GLFW_KEY_RIGHT ] != GLFW_RELEASE ? 2 : @@ -363,7 +363,7 @@ void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) fLastDir = -fLastDir; } /* - if (AIControllFlag) { + if (aiControlled) { // dla AI na razie losujemy kierunek na kolejnym skrzyżowaniu iRouteWanted = 1 + Random(3); } diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index 01453ec32..abc3af4f6 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -511,7 +511,7 @@ TController::control_lights() { } else { // custom light pattern - if( AIControllFlag ) { + if( aiControlled ) { pVehicles[ VehicleEnd::front ]->RaLightsSet( m_lighthints[ VehicleEnd::front ], -1 ); } } @@ -520,7 +520,7 @@ TController::control_lights() { cue_action( driver_hint::headcodepc5 ); } else { - if( AIControllFlag ) { + if( aiControlled ) { pVehicles[ VehicleEnd::rear ]->RaLightsSet( -1, m_lighthints[ VehicleEnd::rear ] ); } } diff --git a/vehicle/ai/speed.cpp b/vehicle/ai/speed.cpp index 1f1a1d343..3d758d35c 100644 --- a/vehicle/ai/speed.cpp +++ b/vehicle/ai/speed.cpp @@ -823,7 +823,7 @@ TController::adjust_desired_speed_for_braking_test() { if( false == is_train() ) { return; } // not applicable if( occupied->brakes.config.driverValveType == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now if( false == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { return; } // not applicable - if( false == AIControllFlag ) { return; } // TBD: add notification about braking test and enable it for human driver as well? + if( false == aiControlled ) { return; } // TBD: add notification about braking test and enable it for human driver as well? auto const vel { DirectionalVel() }; // what the route ahead asks for; the test may brake harder than that, never softer diff --git a/vehicle/ai/speedtable.cpp b/vehicle/ai/speedtable.cpp index 0fb84deae..97a0bd2d3 100644 --- a/vehicle/ai/speedtable.cpp +++ b/vehicle/ai/speedtable.cpp @@ -401,7 +401,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub } } // for human-driven vehicles discard the stop point if they leave it far enough behind - if( false == AIControllFlag + if( false == aiControlled && Point.fDist < -1 * std::max(fLength + 100, 250.0) - Point.fMoved ) { record_station( Point, blackbox::station_kinds::missed ); Point.ResetFlags(); // nie liczy się już zupełnie (nie wyśle SetVelocity) @@ -438,7 +438,7 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub } } else if( true == IsAtPassengerStop ) { // jeśli się zatrzymał przy W4, albo stał w momencie zobaczenia W4 - if( !AIControllFlag ) { + if( !aiControlled ) { // w razie przełączenia na AI ma nie podciągać do W4, gdy użytkownik zatrzymał za daleko drivingFlags.stopCloser = false; } @@ -950,7 +950,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo // NOTE: normally we'd activate the magnet once the leading vehicle passes it // but on a fresh scan after direction change it would be detected as long as it's under consist, and meet the (simple) activation condition // thus we're doing a more precise check in such situation (we presume direction change takes place only if the vehicle is standing still) - occupied->SecuritySystem.set_cabsignal_lock(!AIControllFlag); // don't make life difficult for the ai, but a human driver is a fair game + occupied->SecuritySystem.set_cabsignal_lock(!aiControlled); // don't make life difficult for the ai, but a human driver is a fair game PutCommand(Point.evEvent->input_text(), Point.evEvent->input_value(1), Point.evEvent->input_value(2), nullptr); } if( ismagnetpassed ) { @@ -1060,7 +1060,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo { // to semaphor if( Point.fDist < 0 ) { // for human-driven vehicles ignore the signal if it was passed by sufficient distance - if( false == AIControllFlag + if( false == aiControlled && Point.fDist < -1 * std::max(fLength + 100, 250.0) ) { VelSignal = -1.0; Point.Clear(); @@ -1248,7 +1248,7 @@ TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPo Command = TCommandType::cm_Command; // komenda z komórki, do wykonania po zatrzymaniu } // NOTE: human drivers are likely to stop wherever and expect things to still work, so we give them more leeway - else if (Point.fDist <= (AIControllFlag ? fMaxProximityDist : std::max(250.0, fMaxProximityDist))) + else if (Point.fDist <= (aiControlled ? fMaxProximityDist : std::max(250.0, fMaxProximityDist))) { // jeśli ma dociągnąć, to niech dociąga // (moveStopCloser dotyczy dociągania do W4, nie semafora) diff --git a/vehicle/cab/auxiliarycommands.cpp b/vehicle/cab/auxiliarycommands.cpp index b51faac1a..fa0482117 100644 --- a/vehicle/cab/auxiliarycommands.cpp +++ b/vehicle/cab/auxiliarycommands.cpp @@ -682,7 +682,7 @@ void TTrain::OnCommand_convertertoggle(TTrain *Train, command_data const &Comman if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const overloadrelayisopen{(Train->Dynamic()->Mechanik != nullptr ? Train->Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : Train->occupied->converter.IsOverloaded())}; + auto const overloadrelayisopen{(Train->Dynamic()->Mechanik != nullptr ? Train->Dynamic()->Mechanik->ConsistConverterOverloaded() : Train->occupied->converter.IsOverloaded())}; if (Train->occupied->converter.config.switchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->occupied->lowVoltage.Is110vAvailable() && false == overloadrelayisopen) { @@ -843,7 +843,7 @@ void TTrain::OnCommand_compressortoggle(TTrain *Train, command_data const &Comma if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const compressorisenabled{(Train->Dynamic()->Mechanik ? Train->Dynamic()->Mechanik->IsAnyCompressorEnabled : Train->occupied->air.compressor.IsAllowed())}; + auto const compressorisenabled{(Train->Dynamic()->Mechanik ? Train->Dynamic()->Mechanik->ConsistCompressorEnabled() : Train->occupied->air.compressor.IsAllowed())}; if (false == compressorisenabled) { diff --git a/vehicle/cab/controllercommands.cpp b/vehicle/cab/controllercommands.cpp index b02129e65..469030669 100644 --- a/vehicle/cab/controllercommands.cpp +++ b/vehicle/cab/controllercommands.cpp @@ -59,7 +59,7 @@ void TTrain::OnCommand_aidriverenable(TTrain *Train, command_data const &Command return; } - if (true == Train->DynamicObject->Mechanik->AIControllFlag) + if (true == Train->DynamicObject->Mechanik->AIControllFlag()) { // żeby nie trzeba było rozłączać dla zresetowania Train->DynamicObject->Mechanik->TakeControl(false); diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index 0f4a65b83..63f37ae1b 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -932,7 +932,7 @@ void TTrain::set_cab_controls(int const Cab) // motor connectors ggStLinOffButton.PutValue(controlled->lineContactors.IsForcedOpen() ? 1.f : 0.f); // radio - ggRadioChannelSelector.PutValue(static_cast((Dynamic()->Mechanik ? Dynamic()->Mechanik->iRadioChannel : 1) - 1)); + ggRadioChannelSelector.PutValue(static_cast((Dynamic()->Mechanik ? Dynamic()->Mechanik->RadioChannel() : 1) - 1)); // pantographs /* if( occupied->PantSwitchType != "impulse" ) { diff --git a/vehicle/cab/signalcommands.cpp b/vehicle/cab/signalcommands.cpp index 4b63558af..713aad7c7 100644 --- a/vehicle/cab/signalcommands.cpp +++ b/vehicle/cab/signalcommands.cpp @@ -310,7 +310,7 @@ void TTrain::OnCommand_radiochannelset(TTrain *Train, command_data const &Comman if (Command.action != GLFW_RELEASE) { // on press or hold - Train->RadioChannel() = std::clamp((int)Command.param1, 1, 10); + Train->SetRadioChannel(std::clamp((int)Command.param1, 1, 10)); Train->ggRadioChannelSelector.UpdateValue(static_cast(Train->RadioChannel() - 1)); } } diff --git a/vehicle/cab/sounds.cpp b/vehicle/cab/sounds.cpp index 3e0eb2d6c..69b9287a8 100644 --- a/vehicle/cab/sounds.cpp +++ b/vehicle/cab/sounds.cpp @@ -389,7 +389,7 @@ void TTrain::update_sounds(double const Deltatime) if (m_distancecounterclear) { auto const *owner{(DynamicObject->ctOwner != nullptr ? DynamicObject->ctOwner : DynamicObject->Mechanik)}; - if (m_distancecounter > owner->fLength) + if (m_distancecounter > owner->ConsistLength()) { // play assigned sound if the train travelled its full length since meter activation // TBD: check all combinations of directions and active cab diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 09fb91d76..0a9394ac8 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -146,7 +146,7 @@ bool TTrain::Init(TDynamicObject *NewDynamicObject, bool e3d) controlled->DirectionBackward(); } */ - if (false == DynamicObject->Mechanik->AIControllFlag) + if (false == DynamicObject->Mechanik->AIControllFlag()) { DynamicObject->Mechanik->sync_consist_reversers(); } @@ -364,17 +364,17 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const // ai state data auto const *vehicledriver{(DynamicObject->ctOwner != nullptr ? DynamicObject->ctOwner : DynamicObject->Mechanik)}; - dict->insert("velocity_desired", vehicledriver->VelDesired); - dict->insert("velroad", vehicledriver->VelRoad); - dict->insert("vellimitlast", vehicledriver->VelLimitLast); - dict->insert("velsignallast", vehicledriver->VelSignalLast); - dict->insert("velsignalnext", vehicledriver->VelSignalNext); - dict->insert("velnext", vehicledriver->VelNext); - dict->insert("actualproximitydist", vehicledriver->ActualProximityDist); + dict->insert("velocity_desired", vehicledriver->DesiredVelocity()); + dict->insert("velroad", vehicledriver->RoadVelocity()); + dict->insert("vellimitlast", vehicledriver->LastLimitVelocity()); + dict->insert("velsignallast", vehicledriver->LastSignalVelocity()); + dict->insert("velsignalnext", vehicledriver->NextSignalVelocity()); + dict->insert("velnext", vehicledriver->NextVelocity()); + dict->insert("actualproximitydist", vehicledriver->ProximityDistance()); // train data vehicledriver->TrainTimetable().serialize(dict.get()); - dict->insert("train_atpassengerstop", vehicledriver->IsAtPassengerStop); - dict->insert("train_length", vehicledriver->fLength); + dict->insert("train_atpassengerstop", vehicledriver->AtPassengerStop()); + dict->insert("train_length", vehicledriver->ConsistLength()); // world state data dict->insert("scenario", Global.SceneryFile); dict->insert("hours", static_cast(simulation::Time.data().wHour)); @@ -550,7 +550,7 @@ void TTrain::UpdateCab() // Ra: przesiadka, jeśli AI zmieniło kabinę (a człon?)... if (DynamicObject->Mechanik // może nie być? - && DynamicObject->Mechanik->AIControllFlag && iCabn != ( // numer kabiny (-1: kabina B) + && DynamicObject->Mechanik->AIControllFlag() && iCabn != ( // numer kabiny (-1: kabina B) occupied->CabOccupied() == -1 ? 2 : occupied->CabOccupied())) { @@ -576,7 +576,7 @@ void TTrain::add_distance(double const Distance) bool TTrain::CabChange(int iDirection) { // McZapkie-090902: zmiana kabiny 1->0->2 i z powrotem - if (DynamicObject->Mechanik == nullptr || true == DynamicObject->Mechanik->AIControllFlag) + if (DynamicObject->Mechanik == nullptr || true == DynamicObject->Mechanik->AIControllFlag()) { // jeśli prowadzi AI albo jest w innym członie // jak AI prowadzi, to nie można mu mieszać @@ -659,7 +659,7 @@ void TTrain::MoveToVehicle(TDynamicObject *target) { // let's try to destroy this TTrain and move to already existing one - if (!Dynamic()->Mechanik || !Dynamic()->Mechanik->AIControllFlag) + if (!Dynamic()->Mechanik || !Dynamic()->Mechanik->AIControllFlag()) { // tylko jeśli ręcznie prowadzony // jeśli prowadzi AI, to mu nie robimy dywersji! @@ -682,7 +682,7 @@ void TTrain::MoveToVehicle(TDynamicObject *target) target_train->Dynamic()->MechInside = true; if (target_train->Dynamic()->Mechanik) { - target_train->Dynamic()->Controller = target_train->Dynamic()->Mechanik->AIControllFlag; + target_train->Dynamic()->Controller = target_train->Dynamic()->Mechanik->AIControllFlag(); target_train->Dynamic()->Mechanik->DirectionChange(); } else @@ -716,7 +716,7 @@ void TTrain::MoveToVehicle(TDynamicObject *target) // remove TTrain from global list, we're going to change dynamic anyway simulation::Trains.detach(Dynamic()->name()); - if (!Dynamic()->Mechanik || !Dynamic()->Mechanik->AIControllFlag) + if (!Dynamic()->Mechanik || !Dynamic()->Mechanik->AIControllFlag()) { // tylko jeśli ręcznie prowadzony // jeśli prowadzi AI, to mu nie robimy dywersji! @@ -740,7 +740,7 @@ void TTrain::MoveToVehicle(TDynamicObject *target) Dynamic()->MechInside = true; if (Dynamic()->Mechanik) { - Dynamic()->Controller = Dynamic()->Mechanik->AIControllFlag; + Dynamic()->Controller = Dynamic()->Mechanik->AIControllFlag(); Dynamic()->Mechanik->DirectionChange(); } else diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 4adf31f90..333a5bce3 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -242,16 +242,16 @@ void TTrain::updateDoorAndDirectionStates() // helper variables if (DynamicObject->Mechanik != nullptr) { - m_doors = DynamicObject->Mechanik->IsAnyDoorOpen[VehicleSide::right] || DynamicObject->Mechanik->IsAnyDoorOpen[VehicleSide::left]; - m_doorpermits = DynamicObject->Mechanik->IsAnyDoorPermitActive[VehicleSide::right] || DynamicObject->Mechanik->IsAnyDoorPermitActive[VehicleSide::left]; + m_doors = DynamicObject->Mechanik->ConsistDoorsOpen()[VehicleSide::right] || DynamicObject->Mechanik->ConsistDoorsOpen()[VehicleSide::left]; + m_doorpermits = DynamicObject->Mechanik->ConsistDoorPermits()[VehicleSide::right] || DynamicObject->Mechanik->ConsistDoorPermits()[VehicleSide::left]; m_doorspermitleft = occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right].open_permit && (simulation::Time.data().wSecond % 2 < 1 || occupied->DoorsPermitLightBlinking < 1 || - occupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right] || - (occupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right])); + occupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->ConsistDoorsOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right] || + (occupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->ConsistDoorsOnlyOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right])); m_doorspermitright = occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left].open_permit && (simulation::Time.data().wSecond % 2 < 1 || occupied->DoorsPermitLightBlinking < 1 || - occupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left] || - (occupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left])); + occupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->ConsistDoorsOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left] || + (occupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->ConsistDoorsOnlyOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left])); } m_dirforward = controlled->DirActive > 0; m_dirneutral = controlled->DirActive == 0; @@ -288,7 +288,7 @@ void TTrain::processReceivedCommands() void TTrain::returnMasterController(double const Deltatime) { // nie blokujemy AI - if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag && (occupied->TrainType == train_type::et40 || occupied->TrainType == train_type::ep05 || occupied->HasCamshaft)) + if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag() && (occupied->TrainType == train_type::et40 || occupied->TrainType == train_type::ep05 || occupied->HasCamshaft)) { // dla ET40 i EU05 automatyczne cofanie nastawnika - i tak nie będzie to działać dobrze... // TODO: use deltatime to stabilize speed @@ -609,7 +609,7 @@ void TTrain::updateConverterOverload(double const Deltatime) fConverterTimer += static_cast(Deltatime); if (controlled->air.compressor.IsRunning() == true && controlled->air.compressor.config.supply == physics::CompressorSupply::converterManual && (controlled->EngineType == TEngineType::ElectricSeriesMotor || controlled->TrainType == train_type::emu) && DynamicObject->Controller == Humandriver // hunter-110212: poprawka dla EZT - && DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag) + && DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag()) { // hunter-091012: poprawka (zmiana warunku z CompressorPower /rozne od 0/ na /rowne 1/) if (fConverterTimer < fConverterPrzekaznik) { @@ -834,7 +834,7 @@ void TTrain::updateCircuitLamps(double const Deltatime) btLampkaPrzetw.Turn(occupied->lowVoltage.Is110vAvailable()); btLampkaPrzetwOff.Turn(!occupied->lowVoltage.Is110vAvailable()); btLampkaPrzetwAOff.Turn(!controlled->converter.IsRunning()); - btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : controlled->converter.IsOverloaded()); + btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->ConsistConverterOverloaded() : controlled->converter.IsOverloaded()); btLampkaOpory.Turn(controlled->lineContactors.IsClosed() && controlled->ResistorsFlagCheck()); btLampkaBezoporowa.Turn(controlled->ResistorsFlagCheck() || controlled->MainCtrlActualPos == 0); // do EU04 @@ -924,15 +924,15 @@ void TTrain::updateTrainLamps() // NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu if (DynamicObject->Mechanik != nullptr) { - btLampkaDoorLeft.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right]); - btLampkaDoorRight.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left]); + btLampkaDoorLeft.Turn(DynamicObject->Mechanik->ConsistDoorsOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right]); + btLampkaDoorRight.Turn(DynamicObject->Mechanik->ConsistDoorsOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left]); } if (DynamicObject->Mechanik != nullptr) { // with DoorClosureSignal in the definition of the cab's vehicle, the door closure signalling (SOD) of the whole // consist: lit with all doors closed and locked, blinking with them closed but released, dark with a door open. // without it, the lock of the vehicle's own doors, as before - btLampkaBlokadaDrzwi.Turn(occupied->door_closure_lamp_lit(DynamicObject->Mechanik->DoorClosure, simulation::Time.data().wSecond % 2 < 1)); + btLampkaBlokadaDrzwi.Turn(occupied->door_closure_lamp_lit(DynamicObject->Mechanik->ConsistDoorClosure(), simulation::Time.data().wSecond % 2 < 1)); } else { @@ -1203,7 +1203,7 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) { #ifdef _WIN32 - if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag // nie blokujemy AI + if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag() // nie blokujemy AI && Global.iFeedbackMode == 4 && Global.fCalibrateIn[2][1] != 0.0) { @@ -1272,7 +1272,7 @@ void TTrain::updateBrakeControllers() if (ggBrakeCtrl.SubModel != nullptr) { #ifdef _WIN32 - if (DynamicObject->Mechanik ? (DynamicObject->Mechanik->AIControllFlag ? false : Global.iFeedbackMode == 4 /*|| (Global.bMWDmasterEnable && Global.bMWDBreakEnable)*/) : + if (DynamicObject->Mechanik ? (DynamicObject->Mechanik->AIControllFlag() ? false : Global.iFeedbackMode == 4 /*|| (Global.bMWDmasterEnable && Global.bMWDBreakEnable)*/) : false && Global.fCalibrateIn[0][1] != 0.0) // nie blokujemy AI { // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba // Firleju: dlatego kasujemy i zastepujemy funkcją w Console @@ -1314,7 +1314,7 @@ void TTrain::updateBrakeControllers() if (ggLocalBrake.SubModel != nullptr) { #ifdef _WIN32 - if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag // nie blokujemy AI + if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag() // nie blokujemy AI && occupied->brakes.config.independentValveType == TBrakeHandle::FD1 && Global.iFeedbackMode == 4 && Global.fCalibrateIn[0][1] != 0.0) { // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba @@ -1498,7 +1498,7 @@ void TTrain::updateAuxiliaryButtons(bool const lowvoltagepower) ggWhistleButton.Update(); if (DynamicObject->Mechanik != nullptr) { - ggHelperButton.UpdateValue(static_cast(DynamicObject->Mechanik->HelperState)); + ggHelperButton.UpdateValue(static_cast(DynamicObject->Mechanik->Helper())); } ggHelperButton.Update(); diff --git a/vehicle/crewchange.cpp b/vehicle/crewchange.cpp index 6b5e504ed..9202934f5 100644 --- a/vehicle/crewchange.cpp +++ b/vehicle/crewchange.cpp @@ -59,7 +59,7 @@ vehicle_state state_of(TDynamicObject &Vehicle) { // to tell by, and each of them is driven from its own seat state.has_cab = Vehicle.physics->HasDriverCab() || Vehicle.physics->CategoryFlag != rail_category; state.has_driver = Vehicle.Mechanik != nullptr; - state.driver_is_ai = state.has_driver && Vehicle.Mechanik->AIControllFlag; + 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; diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index bfe675a9e..5b3599f3c 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -337,8 +337,8 @@ void TDynamicObject::distributeInductionBraking( double const dt1 ) } physics::ConsistBrakeBlending::Inputs inputs; inputs.owner = ctOwner != nullptr ? ctOwner->Controlling() : nullptr; - inputs.aiDriving = Mechanik->AIControllFlag; - Mechanik->fMedAmax = brakeBlending.Update( *physics, consist, inputs, dt1 ); + inputs.aiDriving = Mechanik->AIControllFlag(); + Mechanik->SetMedAmax(brakeBlending.Update( *physics, consist, inputs, dt1 )); } // the main switch off, with the supply of the vehicle's circuits off, but for diesel engines and hand cars @@ -1099,7 +1099,7 @@ void TDynamicObject::RadioStop() Mechanik->PutCommand( "Emergency_brake", 1.0, 1.0, &pos, stopRadio ); // add onscreen notification for human driver // TODO: do it selectively for the 'local' driver once the multiplayer is in - if( false == Mechanik->AIControllFlag ) { + if( false == Mechanik->AIControllFlag() ) { ui::Transcripts.AddLine( "!! RADIO-STOP !!", 0.0, 10.0, false ); } } @@ -1119,20 +1119,6 @@ void TDynamicObject::OverheadTrack(float o) // w torze if (ctOwner) // jeśli ma obiekt nadzorujący { // trzeba zaktualizować mapę flag bitowych jazdy bezprądowej - if (o < 0.0) - { // normalna jazda po tym torze - ctOwner->iOverheadZero &= ~iOverheadMask; // zerowanie bitu - może pobierać prąd - ctOwner->iOverheadDown &= ~iOverheadMask; // zerowanie bitu - może podnieść pantograf - } - else if (o > 0.0) - { // opuszczenie pantografów - ctOwner->iOverheadZero |= iOverheadMask; // ustawienie bitu - ma jechać bez pobierania prądu - ctOwner->iOverheadDown |= iOverheadMask; // ustawienie bitu - ma opuścić pantograf - } - else - { // jazda bezprądowa z podniesionym pantografem - ctOwner->iOverheadZero |= iOverheadMask; // ustawienie bitu - ma jechać bez pobierania prądu - ctOwner->iOverheadDown &= ~iOverheadMask; // zerowanie bitu - może podnieść pantograf - } + ctOwner->MarkOverhead( iOverheadMask, o ); } }; diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index 0c5abdd14..9643921c2 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -235,7 +235,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { if( false == vehicle->bEnabled ) { continue; } ++counts.enabled; if( vehicle->physics->CategoryFlag & 2 ) { ++counts.road; } - if( ( vehicle->Mechanik != nullptr ) && vehicle->Mechanik->AIControllFlag ) { ++counts.ai; } + if( ( vehicle->Mechanik != nullptr ) && vehicle->Mechanik->AIControllFlag() ) { ++counts.ai; } if( vehicle->physics->PhysicActivation || vehicle->MechInside ) { ++counts.active; } } diff --git a/vehicle/dynamic/visual.cpp b/vehicle/dynamic/visual.cpp index 49978348a..dbbe3bf06 100644 --- a/vehicle/dynamic/visual.cpp +++ b/vehicle/dynamic/visual.cpp @@ -430,7 +430,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) auto const followsdirection { Global.DriverFigureFollowsDirection && SingleDesk - && false == Mechanik->AIControllFlag }; + && false == Mechanik->AIControllFlag() }; auto const figure { driver_figure::shown( physics->CabOccupied(), physics->DirAbsolute, followsdirection ) }; btMechanik1.Turn( figure > 0 ); btMechanik2.Turn( figure < 0 ); diff --git a/world/Event.cpp b/world/Event.cpp index b1c17dc6b..87cb7a0cd 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -1042,7 +1042,7 @@ whois_event::run_() { m_activator->ctOwner ) }; auto const consistbrakelevel { ( owner != nullptr ? - owner->fReady : + owner->BrakesReleaseLevel() : -1.0 ) }; auto const collisiondistance { ( owner != nullptr ? From 5879c228dc579757a6f6cf0459fb0bdc046e529e Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 13:17:56 +0100 Subject: [PATCH 26/30] refactor(physics): what the rest of the simulator only reads of a vehicle is private to it 53 fields of physics::Vehicle that only the vehicle itself writes, and the rest of the simulator reads, are private, with a query each, named as the field was (Vmax(), TotalMass(), Ft(), nrot(), NAxles(), PhysicActivation(), ...): the compiler now keeps the cab, the AI, the scenery, the renderer and the tests from changing what the definition gives or the physics works out. The fields were picked by what is never written outside the class, of plain types, with no other member of the same name to confuse; inside the class they keep their meaning under camelCase names. The one place outside that cleared a flag of the AI through a reference does it through ClearAIFlag(). No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- application/driverhints.cpp | 28 ++-- application/driveruipanels.cpp | 22 +-- input/drivermouseinput.cpp | 6 +- input/messaging.cpp | 4 +- physics/components/body.cpp | 131 ++++++++--------- physics/components/cab.cpp | 20 +-- physics/components/collisions.cpp | 86 ++++++------ physics/components/commands.cpp | 24 ++-- physics/components/controllers.cpp | 140 +++++++++---------- physics/components/couplers.cpp | 4 +- physics/components/diesel.cpp | 76 +++++----- physics/components/drive.cpp | 14 +- physics/components/electrics.cpp | 10 +- physics/components/fizparser.cpp | 4 +- physics/components/fizsections.cpp | 110 +++++++-------- physics/components/pneumatics.cpp | 40 +++--- physics/components/securitysystem.cpp | 4 +- physics/components/setup.cpp | 32 ++--- physics/components/traction.cpp | 160 ++++++++++----------- physics/consistbraking.cpp | 24 ++-- physics/vehicle.h | 170 +++++++++++++++-------- simulation/blackboxrecorder.cpp | 10 +- tests/unit/drive.cpp | 4 +- tests/unit/figures.cpp | 4 +- tests/unit/golden.cpp | 28 ++-- tests/unit/invariants.cpp | 8 +- tests/unit/test_6dg_power_steps.cpp | 6 +- tests/unit/test_ai_hints.cpp | 12 +- tests/unit/test_brakes.cpp | 10 +- tests/unit/test_cab.cpp | 6 +- tests/unit/test_cntrl.cpp | 8 +- tests/unit/test_collisions.cpp | 74 +++++----- tests/unit/test_commands.cpp | 12 +- tests/unit/test_consist_braking.cpp | 2 +- tests/unit/test_controls.cpp | 8 +- tests/unit/test_couplers_trains.cpp | 2 +- tests/unit/test_crew.cpp | 6 +- tests/unit/test_definition.cpp | 10 +- tests/unit/test_derail_motion.cpp | 22 +-- tests/unit/test_derailment_vehicle.cpp | 10 +- tests/unit/test_diesel.cpp | 6 +- tests/unit/test_dimmer.cpp | 2 +- tests/unit/test_dynamic_brake_diesel.cpp | 20 +-- tests/unit/test_elf_controller.cpp | 28 ++-- tests/unit/test_engine_start.cpp | 2 +- tests/unit/test_equipment_faults.cpp | 8 +- tests/unit/test_field_shunting.cpp | 14 +- tests/unit/test_fiz.cpp | 12 +- tests/unit/test_genset.cpp | 4 +- tests/unit/test_handover.cpp | 14 +- tests/unit/test_horn.cpp | 6 +- tests/unit/test_loads.cpp | 4 +- tests/unit/test_pullee.cpp | 10 +- tests/unit/test_speed_control.cpp | 36 ++--- tests/unit/test_traction.cpp | 10 +- tests/unit/test_uc_steps.cpp | 4 +- tests/unit/test_wheelslip.cpp | 4 +- tests/unit/vehicle.cpp | 8 +- utilities/motiontelemetry.cpp | 2 +- vehicle/ai/consist.cpp | 20 +-- vehicle/ai/controls.cpp | 94 ++++++------- vehicle/ai/driver.cpp | 8 +- vehicle/ai/force.cpp | 8 +- vehicle/ai/physicslog.cpp | 8 +- vehicle/ai/situation.cpp | 20 +-- vehicle/ai/speed.cpp | 10 +- vehicle/brakesetting.cpp | 2 +- vehicle/cab/auxiliarycommands.cpp | 6 +- vehicle/cab/brakecommands.cpp | 8 +- vehicle/cab/cabcommands.cpp | 4 +- vehicle/cab/controllercommands.cpp | 8 +- vehicle/cab/lightcommands.cpp | 10 +- vehicle/cab/powercommands.cpp | 8 +- vehicle/cab/setup.cpp | 30 ++-- vehicle/cab/sounds.cpp | 18 +-- vehicle/cab/train.cpp | 20 +-- vehicle/cab/update.cpp | 74 +++++----- vehicle/dynamic/lifecycle.cpp | 16 +-- vehicle/dynamic/mmd.cpp | 16 +-- vehicle/dynamic/movement.cpp | 4 +- vehicle/dynamic/offtrack.cpp | 14 +- vehicle/dynamic/sounds.cpp | 26 ++-- vehicle/dynamic/update.cpp | 30 ++-- vehicle/dynamic/vehicletable.cpp | 14 +- vehicle/dynamic/visual.cpp | 6 +- vehicle/enginestart.cpp | 2 +- vehicle/handover.cpp | 4 +- widgets/vehicleparams.cpp | 12 +- 88 files changed, 1053 insertions(+), 992 deletions(-) diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 13641f60b..081d21862 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -124,7 +124,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->AutomaticCabActivation || (occupied->CabMaster == false && occupied->CabActive == 0); } ); + return occupied->AutomaticCabActivation || (occupied->CabMaster() == false && occupied->CabActive == 0); } ); break; } // radio @@ -560,7 +560,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) Action, [this](float const /*Parameter*/) { return mvControlling->EIMDirectionChangeAllow(); }, - static_cast(mvControlling->MainCtrlMaxDirChangePos) ); + static_cast(mvControlling->MainCtrlMaxDirChangePos()) ); break; } case driver_hint::tractiveforcedecrease: { @@ -571,12 +571,12 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) { - return std::abs(mvControlling->Ft) <= Parameter; }, + return std::abs(mvControlling->Ft()) <= Parameter; }, static_cast(std::min( 0.0, std::max( - std::abs( mvControlling->Ft ) * 0.95, - std::abs( mvControlling->Ft ) - 5.0 ) )) ); + std::abs( mvControlling->Ft() ) * 0.95, + std::abs( mvControlling->Ft() ) - 5.0 ) )) ); break; } case driver_hint::tractiveforceincrease: { @@ -598,14 +598,14 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::bufferscompress: { - if (aiControlled && std::abs( mvControlling->Ft ) < 50000.0) { + if (aiControlled && std::abs( mvControlling->Ft() ) < 50000.0) { IncSpeed(); } remove_master_controller_hints(); hint( Action, [this](float const /*Parameter*/) { - return std::abs(mvControlling->Ft) > 30.0 || false == OrderCurrentGet().HasAny(DriverOrder::disconnect); } ); + return std::abs(mvControlling->Ft()) > 30.0 || false == OrderCurrentGet().HasAny(DriverOrder::disconnect); } ); break; } @@ -725,7 +725,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvControlling->diesel.heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink == true; } ); + return mvControlling->diesel.heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink() == true; } ); break; } case driver_hint::watercircuitslinkoff: { @@ -736,7 +736,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvControlling->diesel.heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink == false; } ); + return mvControlling->diesel.heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink() == false; } ); break; } case driver_hint::waittemperaturetoolow: { @@ -901,7 +901,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) case driver_hint::independentbrakeapply: { if (aiControlled && occupied->brakes.IndependentPosition() < 1.0) { occupied->IncLocalBrakeLevel( LocalBrakePosNo ); - if (occupied->EIMCtrlEmergency) { + if (occupied->EIMCtrlEmergency()) { occupied->DecLocalBrakeLevel(1); } } @@ -910,7 +910,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) Action, [this](float const Parameter) { return occupied->brakes.IndependentPosition() >= Parameter; }, - ( LocalBrakePosNo - ( occupied->EIMCtrlEmergency ? 1 : 0 ) ) / LocalBrakePosNo ); + ( LocalBrakePosNo - ( occupied->EIMCtrlEmergency() ? 1 : 0 ) ) / LocalBrakePosNo ); break; } case driver_hint::independentbrakerelease: { @@ -980,7 +980,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvControlling->Sand == 0 || mvControlling->SandDose == true || mvControlling->SlippingWheels == false; } ); + return mvControlling->Sand == 0 || mvControlling->SandDose() == true || mvControlling->SlippingWheels() == false; } ); break; } case driver_hint::sandingoff: { @@ -991,7 +991,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvControlling->Sand == 0 || mvControlling->SandDose == false; } ); + return mvControlling->Sand == 0 || mvControlling->SandDose() == false; } ); break; } case driver_hint::antislip: { @@ -1001,7 +1001,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvControlling->brakes.config.antiSlipType != 1 || (mvControlling->brakes.distributor->GetBrakeStatus() & b_asb) != 0 || mvControlling->SlippingWheels == false; } ); + return mvControlling->brakes.config.antiSlipType != 1 || (mvControlling->brakes.distributor->GetBrakeStatus() & b_asb) != 0 || mvControlling->SlippingWheels() == false; } ); break; } // horns diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 1a3963434..e6a8cd768 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -167,7 +167,7 @@ drivingaid_panel::update() { STR_C("Brakes: %5.1f+%-2.0f%c%s"), readout.brake_first, readout.local_brake, - physics->SlippingWheels ? '!' : ' ', + physics->SlippingWheels() ? '!' : ' ', expandedtext.c_str() ); } else { @@ -176,7 +176,7 @@ drivingaid_panel::update() { m_buffer.data(), m_buffer.size(), STR_C("Brakes: %5.1f%c%s"), readout.brake_first, - physics->SlippingWheels ? '!' : ' ', + physics->SlippingWheels() ? '!' : ' ', expandedtext.c_str() ); } @@ -386,11 +386,11 @@ timetable_panel::update() { if( false == owner->is_dmu() && false == owner->is_emu() ) { //odejmij lokomotywy czynne, a przynajmniej aktualną - consistmass -= owner->pVehicle->physics->TotalMass; + consistmass -= owner->pVehicle->physics->TotalMass(); // subtract potential other half of a two-part vehicle - if( auto const *previous { owner->pVehicle->Prev( Coupling::permanent ) }; previous != nullptr ) { consistmass -= previous->physics->TotalMass; } + if( auto const *previous { owner->pVehicle->Prev( Coupling::permanent ) }; previous != nullptr ) { consistmass -= previous->physics->TotalMass(); } auto const *next { owner->pVehicle->Next( Coupling::permanent ) }; - if( next != nullptr ) { consistmass -= next->physics->TotalMass; } + if( next != nullptr ) { consistmass -= next->physics->TotalMass(); } } std::snprintf( m_buffer.data(), m_buffer.size(), @@ -893,10 +893,10 @@ debug_panel::update_section_vehicle( std::vector &Output ) { std::string( isdieselinshuntmode ? to_string( physics.AnPos(), 2 ) + STR(" (shunt mode)") : std::to_string( physics.ScndCtrlPos() ) + "(" + std::to_string( physics.ScndCtrlActualPos ) + ")" ).c_str(), // engine physics.EnginePower, - std::abs( physics.TrainType == train_type::emu ? physics.ShowCurrent( 0 ) : physics.Im ), + std::abs( physics.TrainType() == train_type::emu ? physics.ShowCurrent( 0 ) : physics.Im ), // revolutions std::abs( physics.enrot ) * 60, - std::abs( physics.nrot ) * physics.Transmision.Ratio * 60, + std::abs( physics.nrot() ) * physics.Transmision.Ratio * 60, physics.RventRot * 60, std::abs( physics.MotorBlowers[VehicleEnd::front].revolutions ), std::abs( physics.MotorBlowers[VehicleEnd::rear].revolutions ), @@ -912,7 +912,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { physics.diesel.heat.Ts, physics.diesel.heat.To, physics.diesel.heat.temperatura1, - physics.WaterCircuitsLink ? '-' : '|', + physics.WaterCircuitsLink() ? '-' : '|', physics.diesel.heat.temperatura2 ); textline += m_buffer.data(); } @@ -962,12 +962,12 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Forces:\n tractive: %.1f, brake: %.1f, drag: %.2f%s\nAcceleration:\n tangential: %.2f, normal: %.2f (path radius: %s)\nVelocity: %.2f, distance traveled: %.2f\nPosition: [%.2f, %.2f, %.2f]"), // forces - physics.Ft * 0.001f * ( physics.CabOccupied() ? physics.CabOccupied() : vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabOccupied() : 1 ) + 0.001f, + physics.Ft() * 0.001f * ( physics.CabOccupied() ? physics.CabOccupied() : vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabOccupied() : 1 ) + 0.001f, physics.Fb * 0.001f, physics.FrictionForce() * 0.001f, - physics.SlippingWheels ? " (!)" : "", + physics.SlippingWheels() ? " (!)" : "", // acceleration - physics.AccSVBased, + physics.AccSVBased(), physics.AccN() + 0.001f, std::string( std::abs( physics.RunningShape.R ) > 15000.0 ? "~0" : to_string( physics.RunningShape.R, 0 ) ).c_str(), // velocity diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index 37bc1992c..bc13495b0 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -63,7 +63,7 @@ mouse_slider::bind( user_command const &Command ) { auto const powerrange { static_cast( vehicle->CoupledCtrl ? - vehicle->MainCtrlPosNo + vehicle->ScndCtrlPosNo : + vehicle->MainCtrlPosNo + vehicle->ScndCtrlPosNo() : vehicle->MainCtrlPosNo ) }; // for simplicity upper half of the range controls power, lower controls brakes @@ -79,14 +79,14 @@ mouse_slider::bind( user_command const &Command ) { break; } case user_command::mastercontrollerset: { - m_valuerange = vehicle->CoupledCtrl ? vehicle->MainCtrlPosNo + vehicle->ScndCtrlPosNo : vehicle->MainCtrlPosNo; + m_valuerange = vehicle->CoupledCtrl ? vehicle->MainCtrlPosNo + vehicle->ScndCtrlPosNo() : vehicle->MainCtrlPosNo; m_value = vehicle->CoupledCtrl ? vehicle->MainCtrlPos() + vehicle->ScndCtrlPos() : vehicle->MainCtrlPos(); m_analogue = false; m_invertrange = false; break; } case user_command::secondcontrollerset: { - m_valuerange = vehicle->ScndCtrlPosNo; + m_valuerange = vehicle->ScndCtrlPosNo(); m_value = vehicle->ScndCtrlPos(); m_analogue = false; m_invertrange = true; diff --git a/input/messaging.cpp b/input/messaging.cpp index ce52e718d..4bdb39060 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -277,8 +277,8 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) r.fPar[3] = Vehicle->physics->Loc().Y; // pozycja Y r.fPar[4] = Vehicle->physics->Loc().Z; // pozycja Z r.fPar[5] = Vehicle->physics->V(); // prędkość ruchu X - r.fPar[6] = Vehicle->physics->nrot * M_PI * - Vehicle->physics->WheelDiameter; // prędkość obrotowa kóŁ + r.fPar[6] = Vehicle->physics->nrot() * M_PI * + Vehicle->physics->WheelDiameter(); // prędkość obrotowa kóŁ r.fPar[7] = 0; // prędkość ruchu Z r.fPar[8] = Vehicle->physics->AccS(); // przyspieszenie X r.fPar[9] = Vehicle->physics->AccN(); // przyspieszenie Y //na razie nie diff --git a/physics/components/body.cpp b/physics/components/body.cpp index 507fc9545..bfede4797 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -217,7 +217,7 @@ double physics::Vehicle::ComputeMovement(double dt, double dt1, const TTrackShap } if (CategoryFlag == 4) - offsetTrackV = TotalMass / (Dim.L * Dim.W * 1000.0); + offsetTrackV = totalMass / (Dim.L * Dim.W * 1000.0); else if (TestFlag(CategoryFlag, 1) && TestFlag(RunningTrack.CategoryFlag, 1) && DamageFlag.HasAll(VehicleDamage::derailed)) { offsetTrackV = -0.2; @@ -232,7 +232,7 @@ double physics::Vehicle::ComputeMovement(double dt, double dt1, const TTrackShap { auto const AccSprev{accS}; // przyspieszenie styczne - accS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); + accS = std::lerp(AccSprev, FTotal / totalMass, 0.5); // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one @@ -263,14 +263,14 @@ double physics::Vehicle::ComputeMovement(double dt, double dt1, const TTrackShap } // tangential acceleration, from velocity change - AccSVBased = std::lerp(AccSVBased, (travelSpeed - Vprev) / dt, std::clamp(dt * 3.0, 0.0, 1.0)); + accSVBased = std::lerp(accSVBased, (travelSpeed - Vprev) / dt, std::clamp(dt * 3.0, 0.0, 1.0)); // vertical acceleration accVert = std::abs(accVert) < 0.01 ? 0.0 : accVert * 0.5; // szarpanie /* #ifdef EU07_USE_FUZZYLOGIC - if( FuzzyLogic( ( 10.0 + Track.DamageFlag ) * Mass * Vel / Vmax, 500000.0, p_accn ) ) { + if( FuzzyLogic( ( 10.0 + Track.DamageFlag ) * Mass * Vel / vmax, 500000.0, p_accn ) ) { // Ra: czemu tu masa bez ładunku? AccV /= ( 2.0 * 0.95 + 2.0 * Random() * 0.1 ); // 95-105% of base modifier (2.0) } @@ -346,7 +346,7 @@ double physics::Vehicle::FastComputeMovement(double dt, const TTrackShape & /*Sh { auto const AccSprev{accS}; // przyspieszenie styczne - accS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); + 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 (DamageFlag.HasAll(VehicleDamage::derailed) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) @@ -417,20 +417,20 @@ void physics::Vehicle::compute_movement_(double const Deltatime) // relay settings // adjust motor overload relay threshold - if (EngineType == TEngineType::ElectricSeriesMotor && ImaxHi > ImaxLo) + if (EngineType == TEngineType::ElectricSeriesMotor && imaxHi > imaxLo) { - if (MotorOverloadRelayHighThreshold) + if (motorOverloadRelayHighThreshold) { // set high threshold - if (TrainType != train_type::et42 ? RList[mainCtrlPos].Bn < 2 : mainCtrlPos == 0) + if (trainType != train_type::et42 ? RList[mainCtrlPos].Bn < 2 : mainCtrlPos == 0) { - Imax = ImaxHi; + Imax = imaxHi; } } else { // set low threshold - if (TrainType != train_type::et42 || mainCtrlPos == 0) + if (trainType != train_type::et42 || mainCtrlPos == 0) { - Imax = ImaxLo; + Imax = imaxLo; } } } @@ -620,21 +620,21 @@ bool physics::Vehicle::Sandbox(bool const State, range_t const Notify) { bool result{false}; - if (SandDose != State) + if (sandDose != State) { - if (SandDose == false) + if (sandDose == false) { // switch on if (Sand > 0 && DirActive != 0) { - SandDose = true; + sandDose = true; result = true; } } else { // switch off - SandDose = false; + sandDose = false; result = true; } } @@ -687,7 +687,7 @@ void physics::Vehicle::ComputeConstans(void) double HideModifier; double Curvature; // Ra 2014-07: odwrotność promienia - TotalMassxg = TotalMass * g; // TotalMass*g + TotalMassxg = totalMass * g; // TotalMass*g BearingF = DamageFlag.HasAny(VehicleDamage::bearing) ? 2.0 : 0; HideModifier = 0; // int(Couplers[0].CouplingFlag>0)+int(Couplers[1].CouplingFlag>0); @@ -701,7 +701,7 @@ void physics::Vehicle::ComputeConstans(void) // if (NPoweredAxles > 0) // RollF = RollF * 1.5; //dodatkowe lozyska silnikow - if (NPoweredAxles > 0) // drobna optymalka + if (nPoweredAxles > 0) // drobna optymalka { RollF += 0.025; // if (Ft * Ft < 1) @@ -745,7 +745,7 @@ void physics::Vehicle::ComputeConstans(void) void physics::Vehicle::ComputeMass() { // Ra: na razie tak, ale nie wszędzie masy wirujące się wliczają - TotalMass = Mass + Mred; + totalMass = Mass + mred; if (loadAmount == 0) { @@ -765,7 +765,7 @@ void physics::Vehicle::ComputeMass() loadtypeunitweight = lookup != simulation::Weights.end() ? lookup->second : 1000.f; // legacy default unit weight value } - TotalMass += loadAmount * loadtypeunitweight; + totalMass += loadAmount * loadtypeunitweight; } // ************************************************************************************************* @@ -803,7 +803,7 @@ void physics::Vehicle::ComputeTotalForce(double dt) wake_cause::neighbour); } - if (false == PhysicActivation) + if (false == physicActivation) { return; } @@ -817,12 +817,12 @@ void physics::Vehicle::ComputeTotalForce(double dt) // 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; + 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; + FStand = totalMass * g; } else { @@ -831,8 +831,8 @@ void physics::Vehicle::ComputeTotalForce(double dt) FStand *= 1e20; } } - double old_nrot = abs(nrot); - nrot = v2n(); // przeliczenie prędkości liniowej na obrotową + double old_nrot = abs(nrotValue); + nrotValue = v2n(); // przeliczenie prędkości liniowej na obrotową if (true == TestFlag(brakes.config.method, bp_MHS) && brakePipe.Pressure() < 3.0 // ustawione na sztywno na 3 bar && Vel > 45 && true == TestFlag(brakes.delaySetting, bdelay_M)) @@ -859,30 +859,30 @@ void physics::Vehicle::ComputeTotalForce(double dt) if (Vel > 0.1 // crude trap, to prevent braked stationary vehicles from passing fb > mass * adhesive test && std::abs(Fwheels) > TotalMassxg * Adhesive(RunningTrack.friction)) { - SlippingWheels = true; + slippingWheels = true; } - if (true == SlippingWheels && Vel < 0.1 // the same crude trap: (nearly) stopped vehicle... - && std::abs(nrot * M_PI * WheelDiameter - travelSpeed) < 0.1 / 3.6) // ...with wheels turning at its speed, i.e. locked wheels at the end of a skid + if (true == slippingWheels && Vel < 0.1 // the same crude trap: (nearly) stopped vehicle... + && std::abs(nrotValue * M_PI * wheelDiameter - travelSpeed) < 0.1 / 3.6) // ...with wheels turning at its speed, i.e. locked wheels at the end of a skid { // locked wheels never pass the rotation speed test below once the vehicle stops, and a skidding vehicle // keeps its braking force capped by the sliding adhesion, so the rest of the consist could push it around - SlippingWheels = false; - nrot = travelSpeed / M_PI / WheelDiameter; + slippingWheels = false; + nrotValue = travelSpeed / M_PI / wheelDiameter; } - double temp_nrot = nrot; - if (true == SlippingWheels) + double temp_nrot = nrotValue; + if (true == slippingWheels) { - temp_nrot = ComputeRotatingWheel(Fwheels - Sign(nrot * M_PI * WheelDiameter - travelSpeed) * Adhesive(RunningTrack.friction) * TotalMassxg, dt, nrot); - if (Sign(nrot * M_PI * WheelDiameter - travelSpeed) * Sign(temp_nrot * M_PI * WheelDiameter - travelSpeed) < 0) + temp_nrot = ComputeRotatingWheel(Fwheels - Sign(nrotValue * M_PI * wheelDiameter - travelSpeed) * Adhesive(RunningTrack.friction) * TotalMassxg, dt, nrotValue); + if (Sign(nrotValue * M_PI * wheelDiameter - travelSpeed) * Sign(temp_nrot * M_PI * wheelDiameter - travelSpeed) < 0) { - SlippingWheels = false; - temp_nrot = travelSpeed / M_PI / WheelDiameter; + slippingWheels = false; + temp_nrot = travelSpeed / M_PI / wheelDiameter; } } - if (true == SlippingWheels) + if (true == slippingWheels) { - Fwheels = Sign(temp_nrot * M_PI * WheelDiameter - travelSpeed) * TotalMassxg * Adhesive(RunningTrack.friction); + Fwheels = Sign(temp_nrot * M_PI * wheelDiameter - travelSpeed) * TotalMassxg * Adhesive(RunningTrack.friction); if (Fwheels * Sign(travelSpeed) > 0) { FTrain = Fwheels + Fb * Sign(travelSpeed); @@ -897,14 +897,14 @@ void physics::Vehicle::ComputeTotalForce(double dt) Fb *= factor; FTrain *= factor; } - if (std::abs(nrot) < 0.1) + if (std::abs(nrotValue) < 0.1) { - wheelFlat = sqrt(square(wheelFlat) + abs(Fwheels) / NAxles * Vel * 0.000002); + wheelFlat = sqrt(square(wheelFlat) + abs(Fwheels) / nAxles * Vel * 0.000002); } - nrot = temp_nrot; + nrotValue = temp_nrot; } - nrot_eps = (abs(nrot) - old_nrot) / dt; + nrot_eps = (abs(nrotValue) - old_nrot) / dt; // doliczenie sił z innych pojazdów for (auto const end : VehicleEnds) { @@ -944,7 +944,7 @@ double physics::Vehicle::BrakeForceR(double ratio, double velocity) const ratio = brakes.distributor->GetBrakeRatio(ratio); if (brakes.config.maxPressureMass > 2) { - press = brakes.config.maxCylinderPressure[1] + (brakes.config.maxCylinderPressure[3] - brakes.config.maxCylinderPressure[1]) * std::min(1.0, (TotalMass - Mass) / (brakes.config.maxPressureMass - Mass)); + press = brakes.config.maxCylinderPressure[1] + (brakes.config.maxCylinderPressure[3] - brakes.config.maxCylinderPressure[1]) * std::min(1.0, (totalMass - Mass) / (brakes.config.maxPressureMass - Mass)); } else { @@ -959,7 +959,7 @@ double physics::Vehicle::BrakeForceR(double ratio, double velocity) const ratio = ratio + (1.5 - ratio) * std::min(1.0, Vel * 0.02); if (brakes.delaySetting & bdelay_R && brakes.config.method % 128 != bp_Cosid && brakes.config.method % 128 != bp_D1 && brakes.config.method % 128 != bp_D2 && Power < 1) ratio *= brakes.distributor->GetRapidRatio(velocity); - if (TrainType == train_type::dmu && velocity < 30.0) + if (trainType == train_type::dmu && velocity < 30.0) { ratio -= 0.3; } @@ -972,8 +972,8 @@ double physics::Vehicle::BrakeForceP(double press, double velocity) const { double BFP = 0; double K = ((press * brakes.config.pressureToForce - brakes.config.cylinders.springForce) * brakes.config.cylinders.leverRatio[0] - brakes.config.cylinders.slackAdjusterForce) * brakes.config.cylinders.riggingEfficiency; - K *= static_cast(brakes.config.cylinders.count) / (NAxles * std::max(1, brakes.config.blocksPerAxle)); - BFP = brakes.distributor->GetFC(velocity, K) * K * (NAxles * std::max(1, brakes.config.blocksPerAxle)) * 1000; + K *= static_cast(brakes.config.cylinders.count) / (nAxles * std::max(1, brakes.config.blocksPerAxle)); + BFP = brakes.distributor->GetFC(velocity, K) * K * (nAxles * std::max(1, brakes.config.blocksPerAxle)) * 1000; return BFP; } @@ -1011,7 +1011,7 @@ double physics::Vehicle::BrakeForce(TTrackParam const & /*Track*/) } // the spring brake of a vehicle prepared for hauling (PulleeMode) is released by hand: no force, whatever its cylinder has - if (brakes.spring.isReady && false == PulleeMode) + if (brakes.spring.isReady && false == pulleeMode) K += std::max(0.0, brakes.spring.minForcePressure - brakes.spring.cylinder->P()) * brakes.spring.maxForce; u = (brakes.cylinderPressure * brakes.config.pressureToForce - brakes.config.cylinders.springForce) * brakes.config.cylinders.leverRatio[0] - brakes.config.cylinders.slackAdjusterForce; @@ -1024,7 +1024,7 @@ double physics::Vehicle::BrakeForce(TTrackParam const & /*Track*/) Ntotal = u * (2.0 - brakes.config.cylinders.riggingEfficiency); } - auto const NBrakeAxles{NAxles}; + auto const NBrakeAxles{nAxles}; if (NBrakeAxles * brakes.config.blocksPerAxle > 0) { @@ -1078,9 +1078,9 @@ double physics::Vehicle::Adhesive(double staticfriction) const /* // ABu: male przerobki, tylko czy to da jakikolwiek skutek w FPS? // w kazdym razie zaciemni kod na pewno :) - if (SlippingWheels == false) + if (slippingWheels == false) { - if (SandDose) + if (sandDose) adhesion = (std::max(staticfriction * (100.0 + Vel) / ((50.0 + Vel) * 11.0), 0.048)) * (11.0 - 2.0 * Random(0.0, 1.0)); else @@ -1089,7 +1089,7 @@ double physics::Vehicle::Adhesive(double staticfriction) const } else { - if (SandDose) + if (sandDose) adhesion = (0.048) * (11.0 - 2.0 * Random(0.0, 1.0)); else adhesion = (staticfriction * 0.02) * (11.0 - 2.0 * Random(0.0, 1.0)); @@ -1098,24 +1098,24 @@ double physics::Vehicle::Adhesive(double staticfriction) const return adhesion; //wersja druga - if( true == SlippingWheels ) { + if( true == slippingWheels ) { - if( true == SandDose ) { adhesion = 0.48; } + if( true == sandDose ) { adhesion = 0.48; } else { adhesion = staticfriction * 0.2; } } else { - if( true == SandDose ) { adhesion = std::max( staticfriction * ( 100.0 + Vel ) / ( 50.0 + Vel ) * 1.1, 0.48 ); } + if( true == sandDose ) { adhesion = std::max( staticfriction * ( 100.0 + Vel ) / ( 50.0 + Vel ) * 1.1, 0.48 ); } else { adhesion = staticfriction * ( 100.0 + Vel ) / ( 50.0 + Vel ); } } // adhesion *= ( 0.9 + 0.2 * Random() ); */ // wersja3 by youBy - uwzględnia naturalne mikropoślizgi i wpływ piasecznicy, usuwa losowość z pojazdu - double Vwheels = nrot * M_PI * WheelDiameter; // predkosc liniowa koła wynikająca z obrotowej + double Vwheels = nrotValue * M_PI * wheelDiameter; // predkosc liniowa koła wynikająca z obrotowej double deltaV = travelSpeed - Vwheels; // poślizg - różnica prędkości w punkcie styku koła i szyny deltaV = std::max(0.0, std::abs(deltaV) - 0.25); // mikropoślizgi do ok. 0,25 m/s nie zrywają przyczepności Vwheels = std::abs(Vwheels); - adhesion = staticfriction * (28 + Vwheels) / (14 + Vwheels) * ((SandDose ? sandfactor : 1) - (1 - adh_factor) * (deltaV / (deltaV + slipfactor))); + adhesion = staticfriction * (28 + Vwheels) / (14 + Vwheels) * ((sandDose ? sandfactor : 1) - (1 - adh_factor) * (deltaV / (deltaV + slipfactor))); return adhesion; } @@ -1132,7 +1132,7 @@ double physics::Vehicle::ComputeRotatingWheel(double WForce, double dt, double n newn = 0; else { - eps = WForce * WheelDiameter / (2.0 * AxleInertialMoment); + eps = WForce * wheelDiameter / (2.0 * AxleInertialMoment); newn = n + eps * dt; if (newn * n <= 0 && eps * n < 0) newn = 0; @@ -1262,7 +1262,7 @@ void physics::Vehicle::wake_for_brake() // ************************************************************************************************* bool physics::Vehicle::brakes_changed_asleep() const { - if (PhysicActivation) + if (physicActivation) return false; constexpr double pressure_change{0.05}; // [bar] return std::abs(brakes.cylinderPressure - sleep_brakes.cylinder) > pressure_change || std::abs(brakes.spring.pressure - sleep_brakes.spring) > pressure_change || @@ -1274,12 +1274,12 @@ bool physics::Vehicle::brakes_changed_asleep() const // ************************************************************************************************* bool physics::Vehicle::switch_physics(bool const State, wake_cause const Cause) // DO PRZETLUMACZENIA NA KONCU { - if (PhysicActivation == State) + if (physicActivation == State) { return false; } - PhysicActivation = State; + physicActivation = State; if (true == State) { LastSwitchingTime = 0; @@ -1315,12 +1315,12 @@ void physics::Vehicle::SetEquipmentFaults(EquipmentFaultSet const Faults) if (Faults.HasAll(EquipmentFault::control)) // usterka sterowania { lineContactors.Open(); - if (InitialCtrlDelay < faultthreshold) - InitialCtrlDelay += faultoffset; + if (initialCtrlDelay < faultthreshold) + initialCtrlDelay += faultoffset; } - else if (InitialCtrlDelay > faultthreshold) + else if (initialCtrlDelay > faultthreshold) { - InitialCtrlDelay -= faultoffset; + initialCtrlDelay -= faultoffset; } if (Faults.HasAll(EquipmentFault::converter) && converter.config.start != start_t::disabled) // blokada przetwornicy { @@ -1344,3 +1344,8 @@ void physics::Vehicle::SetEquipmentFaults(EquipmentFaultSet const Faults) // hamowanie nagłe (emergencyBrake): nothing yet equipmentFaults = Faults; } + +void physics::Vehicle::ClearAIFlag(int const Flag) +{ + ClearFlag(aiFlag, Flag); +} diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index 1b421558b..65dd87b91 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -44,7 +44,7 @@ bool physics::Vehicle::DirectionForward() SendCtrlToNext(VehicleCommand::direction, DirActive, CabActive); return true; } - else if (DirActive == 1 && IsMainCtrlNoPowerPos() && TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor) + else if (DirActive == 1 && IsMainCtrlNoPowerPos() && trainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor) return MinCurrentSwitch(true); //"wysoki rozruch" EN57 return false; }; @@ -86,7 +86,7 @@ int physics::Vehicle::SoundingHorns(int const Signal) const return false == mainpipe || mainPipe.Pressure() >= HornMinPressure; }}; auto horns{0}; - if (supplied(HornSupply)) + if (supplied(hornSupply)) { horns |= Signal & (1 | 2); } @@ -106,7 +106,7 @@ bool physics::Vehicle::CabActivisation(bool const Enforce) bool OK = false; OK = Enforce || CabActive == 0; // numer kabiny, z której jest sterowanie - if (PulleeMode) + if (pulleeMode) { // nobody drives from a vehicle prepared for hauling OK = false; @@ -115,7 +115,7 @@ bool physics::Vehicle::CabActivisation(bool const Enforce) { CabActive = cabOccupied; // sterowanie jest z kabiny z obsadą DirAbsolute = DirActive * CabActive; - CabMaster = true; + cabMaster = true; SecuritySystem.set_enabled(true); // activate the alerter TODO: make it part of control based cab selection SendCtrlToNext(VehicleCommand::cabActivation, 1, CabActive); SendCtrlToNext(VehicleCommand::direction, DirActive, CabActive); @@ -165,7 +165,7 @@ bool physics::Vehicle::CabDeactivisation(bool const Enforce) CabActive = 0; DirAbsolute = DirActive * CabActive; - CabMaster = false; + cabMaster = false; DepartureSignal = false; // nie buczeć z nieaktywnej kabiny SecuritySystem.set_enabled(false); // deactivate alerter TODO: make it part of control based cab selection @@ -194,12 +194,12 @@ bool physics::Vehicle::CabDeactivisationAuto(bool const Enforce) // ************************************************************************************************* bool physics::Vehicle::PulleeModeSwitch(bool const State) { - if (PulleeMode == State || (State && CabActive != 0)) + if (pulleeMode == State || (State && CabActive != 0)) { return false; } - PulleeMode = State; - if (PulleeMode) + pulleeMode = State; + if (pulleeMode) { DecManualBrakeLevel(ManualBrakePosNo); brakes.spring.activate = false; @@ -220,7 +220,7 @@ bool physics::Vehicle::DirectionBackward(void) return false; } - if (DirActive == 1 && mainCtrlPos == 0 && TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor && MinCurrentSwitch(false)) + if (DirActive == 1 && mainCtrlPos == 0 && trainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor && MinCurrentSwitch(false)) { return true; } @@ -245,6 +245,6 @@ bool physics::Vehicle::EIMDirectionChangeAllow(void) const // NOTE: disabled while eimic variables aren't immediately synced with master controller changes inside ai module OK = (EngineType != TEngineType::ElectricInductionMotor || ((eimic <= 0) && (eimic_real <= 0) && (Vel < 0.1))); */ - OK = mainCtrlPos <= MainCtrlMaxDirChangePos; + OK = mainCtrlPos <= mainCtrlMaxDirChangePos; return OK; } diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index 4d62b829e..687466138 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -116,12 +116,12 @@ void physics::Vehicle::CollisionDetect(VehicleEnd const End, double const dt) { case VehicleEnd::front: { - CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, loss, VirtualCoupling) / dt; + CCF = ComputeCollision(velocity, othervehiclevelocity, totalMass, othervehicle->totalMass, loss, VirtualCoupling) / dt; break; // yB: ej ej ej, a po } case VehicleEnd::rear: { - CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, loss, VirtualCoupling) / dt; + CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->totalMass, totalMass, loss, VirtualCoupling) / dt; break; } default: @@ -152,11 +152,11 @@ void physics::Vehicle::CollisionDetect(VehicleEnd const End, double const dt) WriteLog("Bad driving: " + Name + " and " + othervehicle->Name + " collided with velocity " + to_string(velocitydifference, 0) + " km/h"); } - if (velocitydifference > SafeCollisionVelocity * (TotalMass / othervehicle->TotalMass)) + if (velocitydifference > SafeCollisionVelocity * (totalMass / othervehicle->totalMass)) { Derail(COLLISION); } - if (velocitydifference > SafeCollisionVelocity * (othervehicle->TotalMass / TotalMass)) + if (velocitydifference > SafeCollisionVelocity * (othervehicle->totalMass / totalMass)) { othervehicle->Derail(COLLISION); } @@ -260,17 +260,17 @@ void physics::Vehicle::derail_in_collision(DerailReason const Reason, std::strin } // upright, it slides on the sleepers and keeps passing the forces on Derailed = derailment::outcome::off_rails; - DerailCause = derail_motion::cause::collision; - DerailAcceleration = 0.0; - DerailSide = 0; - CollisionDerail = Reason; + 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; + nrotValue = 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); @@ -379,8 +379,8 @@ bool physics::Vehicle::crush_hit(VehicleEnd const End, double const dt) return false; } constexpr double immovable{1e12}; - auto const mass{wall ? immovable : TotalMass}; - auto const othermass{otherwall ? immovable : othervehicle->TotalMass}; + 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)}; @@ -410,8 +410,8 @@ bool physics::Vehicle::crush_hit(VehicleEnd const End, double const dt) collision::override_input climbing; climbing.crush1 = Crush1; climbing.crush2 = Crush2; - climbing.mass1 = TotalMass - Mred; - climbing.mass2 = othervehicle->TotalMass - othervehicle->Mred; + 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()); @@ -425,7 +425,7 @@ bool physics::Vehicle::crush_hit(VehicleEnd const End, double const dt) { thiscoupler.crush_monitored = true; othercoupler.crush_monitored = true; - ++crush_reports; + ++crushreportsValue; auto const crush1{thiscoupler.crush + hit.crush1}; auto const crush2{othercoupler.crush + hit.crush2}; auto const climbed{collision::override_of(climbing_of(crush1, crush2))}; @@ -436,8 +436,8 @@ bool physics::Vehicle::crush_hit(VehicleEnd const End, double const dt) : 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)); + 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; } @@ -480,8 +480,8 @@ bool physics::Vehicle::crush_hit(VehicleEnd const End, double const dt) 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, + 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); }; @@ -548,11 +548,11 @@ void physics::Vehicle::check_pushed_off(double const dt, double const Distance) return; } collision::pushed_vehicle vehicle; - vehicle.mass = TotalMass - Mred; - vehicle.axles = NAxles > 0 ? NAxles : 4; + 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; + vehicle.pivots = bDist; + vehicle.axle_base = aDist > 0.0 ? aDist : bDist; auto climbs{false}; auto distance{0.0}; @@ -670,7 +670,7 @@ double physics::Vehicle::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 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); } @@ -683,10 +683,10 @@ void physics::Vehicle::check_derailment(TTrackShape const &Shape, TTrackParam co return; } derailment::vehicle_state vehicle; - vehicle.mass = TotalMass - Mred; - vehicle.axles = NAxles > 0 ? NAxles : 4; + vehicle.mass = totalMass - mred; + vehicle.axles = nAxles > 0 ? nAxles : 4; vehicle.length = Dim.L; - vehicle.axle_base = ADist > 0.0 ? ADist : BDist; + vehicle.axle_base = aDist > 0.0 ? aDist : bDist; vehicle.centre_of_gravity = centre_of_gravity(); for (auto const end : VehicleEnds) { @@ -724,7 +724,7 @@ void physics::Vehicle::check_derailment(TTrackShape const &Shape, TTrackParam co return; } derailment_reported = Track.Name; - ++derailment_reports; + ++derailmentreportsValue; WriteLog("derailment monitor: " + Name + " " + derailment::report(verdict, vehicle, track, travelSpeed, Track.Name != nullptr ? *Track.Name : std::string{})); } @@ -735,10 +735,10 @@ void physics::Vehicle::derail(derailment::verdict const &Verdict, derailment::ve return; } Derailed = Verdict.result; - DerailCause = Verdict.result == derailment::outcome::overturned ? derail_motion::cause::overturned : derail_motion::cause::off_rails; + 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; + 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 @@ -757,14 +757,14 @@ void physics::Vehicle::rerail() 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; + derailCause = derail_motion::cause::off_rails; + derailAcceleration = 0.0; + derailSide = 0; derailment_monitor.reset(); derailmentDistance = 0.0; derailment_reported.reset(); // nor derailed in a collision - CollisionDerail = NONE; + 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) @@ -814,17 +814,17 @@ void physics::Vehicle::Derail(DerailReason const Reason) if (Vel < 5.0) { // HACK: prevent permanent axle spin in static vehicle after a collision - nrot = 0.0; - SlippingWheels = false; + nrotValue = 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; + derailCause = derail_motion::cause::end_of_track; + derailAcceleration = 0.0; + derailSide = 0; tear_brake_hoses(*this); } @@ -858,9 +858,9 @@ void physics::Vehicle::pull_off(int const Side, double const Acceleration, std:: } // 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; + derailCause = derail_motion::cause::pulled_off; + derailAcceleration = Acceleration; + derailSide = Side; eventFlag = true; MainSwitch(false, range_t::local); tear_brake_hoses(*this); diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 50e26c96d..2fd4228da 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -142,9 +142,9 @@ bool physics::Vehicle::RunControllerCommand(VehicleCommand const Command, double if (auto const position{MainCtrlPosFromCoupled(static_cast(floor(CValue1)))}; MainCtrlPosNo >= position) { mainCtrlPos = position; - if (DelayCtrlFlag) + if (delayCtrlFlag) { - if (lineContactors.TimeSinceSwitch() >= InitialCtrlDelay && mainCtrlPos == 1) + if (lineContactors.TimeSinceSwitch() >= initialCtrlDelay && mainCtrlPos == 1) lineContactors.RestartSwitchTimer(); } else if (lineContactors.TimeSinceSwitch() > CtrlDelay) @@ -154,7 +154,7 @@ bool physics::Vehicle::RunControllerCommand(VehicleCommand const Command, double } else if (Command == VehicleCommand::secondaryController) { - if (ScndCtrlPosNo >= floor(CValue1)) + if (scndCtrlPosNo >= floor(CValue1)) { scndCtrlPos = static_cast(floor(CValue1)); if (lineContactors.TimeSinceSwitch() > CtrlDelay) @@ -193,10 +193,10 @@ bool physics::Vehicle::RunRelaysCommand(VehicleCommand const Command, double CVa } else if (Command == VehicleCommand::autoRelaySwitch) { - if (CValue1 == 1 && AutoRelayType == 2) - AutoRelayFlag = true; + if (CValue1 == 1 && autoRelayType == 2) + autoRelayFlag = true; else - AutoRelayFlag = false; + autoRelayFlag = false; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else if (Command == VehicleCommand::maxCurrentSwitch) @@ -240,18 +240,18 @@ bool physics::Vehicle::RunCabCommand(VehicleCommand const Command, double CValue break; } } - if (PulleeMode) + if (pulleeMode) { // a vehicle prepared for hauling takes no cab, the command only passes through it CabActive = 0; } DirAbsolute = DirActive * CabActive; - CabMaster = false; + cabMaster = false; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else if (Command == VehicleCommand::speedControl) { - if (EngineType == TEngineType::ElectricInductionMotor || SpeedCtrl) + if (EngineType == TEngineType::ElectricInductionMotor || speedCtrl) SpeedCtrlValue = static_cast(round(CValue1)); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } @@ -370,7 +370,7 @@ bool physics::Vehicle::RunAuxiliariesCommand(VehicleCommand const Command, doubl else if (Command == VehicleCommand::batterySwitch) /*NBMX*/ { // the battery of a vehicle prepared for hauling (PulleeMode) stays off - if (false == PulleeMode || CValue1 <= 0.0) + if (false == pulleeMode || CValue1 <= 0.0) { lowVoltage.SwitchBattery(CValue1 > 0.0); } @@ -463,7 +463,7 @@ bool physics::Vehicle::RunPumpsCommand(VehicleCommand const Command, double CVal if (true == diesel.heat.auxiliary_water_circuit) { // can only link circuits if the vehicle has more than one of them - WaterCircuitsLink = CValue1 == 1; + waterCircuitsLink = CValue1 == 1; } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } @@ -594,7 +594,7 @@ bool physics::Vehicle::RunPowerCommand(VehicleCommand const Command, double CVal auto const inputend{(static_cast(CValue1) & 0x80) != 0 ? 1 : 0}; auto const inputcab{(static_cast(CValue1) & 0x40) != 0 ? 1 : 0}; auto const inputoperation{static_cast(CValue1) & ~(0x80 | 0x40)}; - auto const noswap{TrainType == train_type::emu || TrainType == train_type::et41}; + auto const noswap{trainType == train_type::emu || trainType == train_type::et41}; auto swap{false == noswap && Couplers[CValue2 == -1 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)}; if (auto const reversed{inputcab != (CabActive != -1 ? 1 : 0)}; reversed) { diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp index e54a8beb5..364feb8be 100644 --- a/physics/components/controllers.cpp +++ b/physics/components/controllers.cpp @@ -48,12 +48,12 @@ bool physics::Vehicle::IncMainCtrl(int CtrlSpeed) // nie ma sterowania return false; } - if (TrainType == train_type::et22 && scndCtrlPos != 0) + if (trainType == train_type::et22 && scndCtrlPos != 0) { // w ET22 nie da się kręcić nastawnikiem przy włączonym boczniku return false; } - if (TrainType == train_type::emu && DirActive == 0) + if (trainType == train_type::emu && DirActive == 0) { // w EZT nie da się załączyć pozycji bez ustawienia kierunku return false; @@ -69,7 +69,7 @@ bool physics::Vehicle::IncMainCtrl(int CtrlSpeed) if (true == CoupledCtrl) { // wspólny wał nastawnika jazdy i bocznikowania - if (scndCtrlPos < ScndCtrlPosNo) + if (scndCtrlPos < scndCtrlPosNo) { // 3<3 -> false ++scndCtrlPos; OK = true; @@ -95,9 +95,9 @@ bool physics::Vehicle::IncMainCtrl(int CtrlSpeed) if (OK) { - if (DelayCtrlFlag) + if (delayCtrlFlag) { - if (lineContactors.TimeSinceSwitch() >= InitialCtrlDelay && mainCtrlPos == 1) + if (lineContactors.TimeSinceSwitch() >= initialCtrlDelay && mainCtrlPos == 1) lineContactors.RestartSwitchTimer(); } else if (lineContactors.TimeSinceSwitch() > CtrlDelay) @@ -125,7 +125,7 @@ bool physics::Vehicle::IncMainCtrlSeriesMotor(int const CtrlSpeed) if (CtrlSpeed > 1) { // szybkie przejœcie na bezoporow¹ - if (TrainType == train_type::et40) + if (trainType == train_type::et40) { return false; // this means ET40 won't react at all to fast acceleration command. should it issue just IncMainCtrl(1) instead? } @@ -143,7 +143,7 @@ bool physics::Vehicle::IncMainCtrlSeriesMotor(int const CtrlSpeed) { // CtrlSpeed == 1 ++mainCtrlPos; OK = true; - if (Imax == ImaxHi && RList[mainCtrlPos].Bn > 1) + if (Imax == imaxHi && RList[mainCtrlPos].Bn > 1) { /* NOTE: disabled, relay configuration was moved to compute_movement_ if( true == MaxCurrentSwitch( false )) { @@ -151,7 +151,7 @@ bool physics::Vehicle::IncMainCtrlSeriesMotor(int const CtrlSpeed) SetFlag( soundFlag, sound::relay ); } */ - if (TrainType == train_type::et42) + if (trainType == train_type::et42) { --mainCtrlPos; OK = false; @@ -167,7 +167,7 @@ bool physics::Vehicle::IncMainCtrlSeriesMotor(int const CtrlSpeed) //} } - if (TrainType == train_type::et42 && true == brakes.electrodynamic.on && mainCtrlPos > 20) + if (trainType == train_type::et42 && true == brakes.electrodynamic.on && mainCtrlPos > 20) { mainCtrlPos = 20; OK = false; @@ -197,7 +197,7 @@ bool physics::Vehicle::DecMainCtrl(int CtrlSpeed) // TBD, TODO: replace with mainctrlpowerpos() check? if (mainCtrlPos > 0) { - if (TrainType != train_type::et22 || scndCtrlPos == 0) // Ra: ET22 blokuje nastawnik przy boczniku + if (trainType != train_type::et22 || scndCtrlPos == 0) // Ra: ET22 blokuje nastawnik przy boczniku { if (CoupledCtrl && scndCtrlPos > 0) { @@ -224,9 +224,9 @@ bool physics::Vehicle::DecMainCtrl(int CtrlSpeed) // hunter-101012: poprawka if (OK) { - if (DelayCtrlFlag) + if (delayCtrlFlag) { - if (lineContactors.TimeSinceSwitch() >= InitialCtrlDelay) + if (lineContactors.TimeSinceSwitch() >= initialCtrlDelay) lineContactors.RestartSwitchTimer(); } else if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) @@ -323,7 +323,7 @@ int physics::Vehicle::MainCtrlPowerPos() const int physics::Vehicle::EIMCtrlEmergencyPositions() const { - return (EIMCtrlType == 2 && EIMCtrlMainEmergency) ? 1 : 0; + return (EIMCtrlType == 2 && eimCtrlMainEmergency) ? 1 : 0; } bool physics::Vehicle::IsMainCtrlEmergencyPos() const @@ -350,20 +350,20 @@ bool physics::Vehicle::IncScndCtrl(int CtrlSpeed) { bool OK = false; - if (brakes.electrodynamic.on && TrainType == train_type::et42 && CabActive != 0 && IsMainCtrlNoPowerPos() && scndCtrlPos == 0) + if (brakes.electrodynamic.on && trainType == train_type::et42 && CabActive != 0 && IsMainCtrlNoPowerPos() && scndCtrlPos == 0) { OK = DynamicBrakeSwitch(false); } - else if (ScndCtrlPosNo > 0 && CabActive != 0 && !(TrainType == train_type::et42 && (Imax == ImaxHi || (brakes.electrodynamic.on && MainCtrlPowerPos() > 0)))) + else if (scndCtrlPosNo > 0 && CabActive != 0 && !(trainType == train_type::et42 && (Imax == imaxHi || (brakes.electrodynamic.on && MainCtrlPowerPos() > 0)))) { // if (RList[mainCtrlPos].R=0) and (mainCtrlPos>0) and (scndCtrlPos 1) { - scndCtrlPos = ScndCtrlPosNo; // takie chamskie, potem poprawie + scndCtrlPos = scndCtrlPosNo; // takie chamskie, potem poprawie } OK = true; } @@ -395,7 +395,7 @@ bool physics::Vehicle::IncScndCtrl(int CtrlSpeed) if (OK && lineContactors.TimeSinceSwitch() > CtrlDelay) lineContactors.RestartSwitchTimer(); - if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1 && mainCtrlPos > 0) + if (OK && EngineType == TEngineType::ElectricInductionMotor && scndCtrlPosNo == 1 && mainCtrlPos > 0) { SpeedCtrlValue = Vel; if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1) @@ -405,7 +405,7 @@ bool physics::Vehicle::IncScndCtrl(int CtrlSpeed) SpeedCtrlUnit.IsActive = true; } - if (OK && SpeedCtrl && scndCtrlPos == 1 && EngineType == TEngineType::DieselEngine) + if (OK && speedCtrl && scndCtrlPos == 1 && EngineType == TEngineType::DieselEngine) { // NOTE: round() already adds 0.5, are the ones added here as well correct? SpeedCtrlValue = static_cast(Round(Vel)); @@ -423,14 +423,14 @@ bool physics::Vehicle::DecScndCtrl(int CtrlSpeed) { bool OK = false; - if (IsMainCtrlNoPowerPos() && CabActive != 0 && TrainType == train_type::et42 && scndCtrlPos == 0 && !brakes.electrodynamic.on && CtrlSpeed == 1) + if (IsMainCtrlNoPowerPos() && CabActive != 0 && trainType == train_type::et42 && scndCtrlPos == 0 && !brakes.electrodynamic.on && CtrlSpeed == 1) { // Ra: AI wywołuje z CtrlSpeed=2 albo gdy scndCtrlPos>0 OK = DynamicBrakeSwitch(true); } - else if (ScndCtrlPosNo > 0 && CabActive != 0) + else if (scndCtrlPosNo > 0 && CabActive != 0) { - if (scndCtrlPos > 0 && !CoupledCtrl && (EngineType != TEngineType::DieselElectric || !AutoRelayFlag) && !IsScndCtrlLockedByMainCtrl()) + if (scndCtrlPos > 0 && !CoupledCtrl && (EngineType != TEngineType::DieselElectric || !autoRelayFlag) && !IsScndCtrlLockedByMainCtrl()) { if (CtrlSpeed == 1) { @@ -457,7 +457,7 @@ bool physics::Vehicle::DecScndCtrl(int CtrlSpeed) if (OK && lineContactors.TimeSinceSwitch() > CtrlDownDelay) lineContactors.RestartSwitchTimer(); - if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1) + if (OK && EngineType == TEngineType::ElectricInductionMotor && scndCtrlPosNo == 1) { SpeedCtrlValue = 0; SpeedCtrlUnit.IsActive = false; @@ -467,7 +467,7 @@ bool physics::Vehicle::DecScndCtrl(int CtrlSpeed) } } - if (OK && SpeedCtrl && scndCtrlPos == 0 && EngineType == TEngineType::DieselEngine) + if (OK && speedCtrl && scndCtrlPos == 0 && EngineType == TEngineType::DieselEngine) { SpeedCtrlValue = 0; SpeedCtrlUnit.IsActive = false; @@ -498,7 +498,7 @@ void physics::Vehicle::ScndCtrlResistiveLockCheck() int physics::Vehicle::GetVirtualScndPos() const { - if (TrainType == train_type::et42 && brakes.electrodynamic.on && !scndCtrlPos) + if (trainType == train_type::et42 && brakes.electrodynamic.on && !scndCtrlPos) return -1; return scndCtrlPos; } @@ -506,13 +506,13 @@ int physics::Vehicle::GetVirtualScndPos() const bool physics::Vehicle::IsScndCtrlNoPowerPos() const { // TODO: refine the check on account of potential electric series vehicles with speed control - return scndCtrlPos == 0 || true == SpeedCtrl; + return scndCtrlPos == 0 || true == speedCtrl; } bool physics::Vehicle::IsScndCtrlMaxPowerPos() const { // TODO: refine the check on account of potential electric series vehicles with speed control - return scndCtrlPos == ScndCtrlPosNo || true == SpeedCtrl; + return scndCtrlPos == scndCtrlPosNo || true == speedCtrl; } // ************************************************************************************************* @@ -522,9 +522,9 @@ bool physics::Vehicle::IsScndCtrlMaxPowerPos() const bool physics::Vehicle::AutoRelaySwitch(bool State) { bool ARS; - if (AutoRelayType == 2 && AutoRelayFlag != State) + if (autoRelayType == 2 && autoRelayFlag != State) { - AutoRelayFlag = State; + autoRelayFlag = State; ARS = true; SendCtrlToNext(VehicleCommand::autoRelaySwitch, int(State), CabActive); } @@ -559,9 +559,9 @@ bool physics::Vehicle::AutoRelayCheck(void) } // sprawdzenie wszystkich warunkow (AutoRelayFlag, AutoSwitch, Im scndCtrlPos) { - if (lineContactors.TimeSinceSwitch() > CtrlDownDelay && TrainType != train_type::emu) + if (lineContactors.TimeSinceSwitch() > CtrlDownDelay && trainType != train_type::emu) { --ScndCtrlActualPos; SetFlag(soundFlag, sound::shuntfield); @@ -626,11 +626,11 @@ bool physics::Vehicle::AutoRelayMainStep(bool const ARFASI) // 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 != train_type::pseudodiesel && RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed}; + auto const backwardslimit{DirActive < 0 && trainType != train_type::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 == train_type::et22 && DelayCtrlFlag))) + (trainType == train_type::et22 && delayCtrlFlag))) { OK = AutoRelayMainUp(ARFASI); } @@ -695,19 +695,19 @@ bool physics::Vehicle::AutoRelayMainNotchUp() bool OK = false; // WriteLog("LRT = " + FloatToStr(LastRelayTime) + ", " + // FloatToStr(CtrlDelay)); - if (TrainType == train_type::et22 && mainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || DelayCtrlFlag)) + if (trainType == train_type::et22 && mainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || delayCtrlFlag)) { // et22 z walem grupowym - if (!DelayCtrlFlag) // najpierw przejscie + if (!delayCtrlFlag) // najpierw przejscie { ++MainCtrlActualPos; - DelayCtrlFlag = true; // tryb przejscia + delayCtrlFlag = true; // tryb przejscia OK = true; } else if (lineContactors.TimeSinceSwitch() > 4 * CtrlDelay) // przejscie { - DelayCtrlFlag = false; + delayCtrlFlag = false; OK = true; } /* @@ -755,7 +755,7 @@ bool physics::Vehicle::AutoRelayMainDown() } else if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) { - if (TrainType != train_type::emu) // tutaj powinien być tryb sterowania wałem + if (trainType != train_type::emu) // tutaj powinien być tryb sterowania wałem { --MainCtrlActualPos; OK = true; @@ -775,22 +775,22 @@ bool physics::Vehicle::AutoRelayLineContactorsStep(bool const motorconnectorsoff { bool OK = false; // ybARC - zalaczenie stycznikow liniowych - if (false == motorconnectorsoff && MainCtrlActualPos == 0 && (TrainType == train_type::emu || HasCamshaft ? MainCtrlPowerPos() > 0 : MainCtrlPowerPos() == 1)) + if (false == motorconnectorsoff && MainCtrlActualPos == 0 && (trainType == train_type::emu || HasCamshaft ? MainCtrlPowerPos() > 0 : MainCtrlPowerPos() == 1)) { - DelayCtrlFlag = true; - if (lineContactors.TimeSinceSwitch() >= InitialCtrlDelay) + delayCtrlFlag = true; + if (lineContactors.TimeSinceSwitch() >= initialCtrlDelay) { lineContactors.Close(); MainCtrlActualPos = 1; - DelayCtrlFlag = false; + delayCtrlFlag = false; SetFlag(soundFlag, sound::relay | sound::loud); OK = true; } } else { - DelayCtrlFlag = false; + delayCtrlFlag = false; } if (false == lineContactors.IsClosed() && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) @@ -809,7 +809,7 @@ bool physics::Vehicle::CamshaftRunDown() if (CoupledCtrl) { - if (TrainType == train_type::emu) + if (trainType == train_type::emu) { OK = CamshaftRunDownEMU(); } @@ -871,7 +871,7 @@ bool physics::Vehicle::CamshaftRunDownEMU() // dojdz do konca ++MainCtrlActualPos; } - else if (ScndCtrlActualPos < ScndCtrlPosNo) + else if (ScndCtrlActualPos < scndCtrlPosNo) { // potem boki ++ScndCtrlActualPos; @@ -993,7 +993,7 @@ double stepped_uc_value(double const Current, double const Ramped, TUniversalCtr void physics::Vehicle::CheckEIMIC(double dt) { double offset = EIMCtrlAdditionalZeros ? 1.0 : 0.0; - double multiplier = (EIMCtrlEmergency ? 1.0 : 0.0) + offset; + double multiplier = (eimCtrlEmergency ? 1.0 : 0.0) + offset; // gdy SplitEDPneumaticBrake jest wlaczone, sterowanie ujemne (hamowanie ED) bierzemy // z osobnego nastawnika DynamicBrakeCtrl, a nie z hamulca pomocniczego (LocalBrake). // Dodatkowo zapotrzebowanie ED jest ograniczone przez strefe Vh0..Vh1: powyzej Vh1 - pelny ED, @@ -1037,7 +1037,7 @@ void physics::Vehicle::CheckEIMIC(double dt) void physics::Vehicle::EIMICFromController(double const brakeDemand, double const offset, double const multiplier) { eimic = brakeDemand > 0.01 ? -brakeDemand : eimicAnalog > 0.01 ? eimicAnalog : (double)mainCtrlPos / (double)MainCtrlPosNo; - if (EIMCtrlAdditionalZeros || EIMCtrlEmergency) + if (EIMCtrlAdditionalZeros || eimCtrlEmergency) { if (eimic > 0.001) eimic = std::max(0.002, eimic * (double)MainCtrlPosNo / ((double)MainCtrlPosNo - offset) - offset / ((double)MainCtrlPosNo - offset)); @@ -1092,7 +1092,7 @@ void physics::Vehicle::EIMICFromFourPositions(double dt) // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() eimic = -1.0; } - else if (MainCtrlActualPos != mainCtrlPos || lineContactors.TimeSinceSwitch() > InitialCtrlDelay) + else if (MainCtrlActualPos != mainCtrlPos || lineContactors.TimeSinceSwitch() > initialCtrlDelay) { double delta = MainCtrlActualPos == mainCtrlPos ? dt * CtrlDelay : 0.01; // the positions below are those of the controller without the emergency brake position @@ -1136,7 +1136,7 @@ void physics::Vehicle::EIMICFromUniversalController(double dt, double const brak UniversalControllerTrainBrake(); } - if (MainCtrlActualPos != mainCtrlPos || lineContactors.TimeSinceSwitch() > InitialCtrlDelay) + if (MainCtrlActualPos != mainCtrlPos || lineContactors.TimeSinceSwitch() > initialCtrlDelay) { auto const &position{UniCtrlList[mainCtrlPos]}; double ramped{eimic}; @@ -1145,7 +1145,7 @@ void physics::Vehicle::EIMICFromUniversalController(double dt, double const brak 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; + eimic = uniCtrlValStep > 0.0 ? stepped_uc_value(eimic, ramped, position, uniCtrlValStep, MainCtrlActualPos != mainCtrlPos, eimic_step_progress) : ramped; } if (MainCtrlActualPos == mainCtrlPos) lineContactors.AdvanceSwitchTimer(dt); @@ -1154,9 +1154,9 @@ void physics::Vehicle::EIMICFromUniversalController(double dt, double const brak lineContactors.RestartSwitchTimer(); MainCtrlActualPos = mainCtrlPos; } - if (brakes.distributor->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake + if (brakes.distributor->GetEDBCP() > 0.3 && eimic < 0 && !uniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake eimic = 0; // shut off retarder - if (UniCtrlIntegratedBrakeCtrl == false && UniCtrlIntegratedLocalBrakeCtrl == false) + if (UniCtrlIntegratedBrakeCtrl == false && uniCtrlIntegratedLocalBrakeCtrl == false) { // w trybie SplitEDPneumaticBrake hamowanie ED przychodzi z osobnego nastawnika, // LocalBrake operuje wylacznie pneumatycznym hamulcem lokomotywy @@ -1258,7 +1258,7 @@ void physics::Vehicle::CheckSpeedCtrl(double dt) if (EIMCtrlType >= 3 && UniCtrlList[mainCtrlPos].SpeedUp <= 0) { accfactor = 0.0; - eimicSpeedCtrl = 0; + eimicSpeedCtrlValue = 0; } } if (SpeedCtrlUnit.IsActive) @@ -1271,7 +1271,7 @@ void physics::Vehicle::CheckSpeedCtrl(double dt) } else { - eimicSpeedCtrl = 0; + eimicSpeedCtrlValue = 0; eimicSpeedCtrlIntegral = 0; } SpeedCtrlUnit.Parking = Vel == 0.0 && eimic <= 0 && EngineType != TEngineType::ElectricInductionMotor; @@ -1279,10 +1279,10 @@ void physics::Vehicle::CheckSpeedCtrl(double dt) } else { - if (Vmax < 250) - eimicSpeedCtrl = std::clamp(0.5 * (SpeedCtrlValue - Vel), -1.0, 1.0); + if (vmax < 250) + eimicSpeedCtrlValue = std::clamp(0.5 * (SpeedCtrlValue - Vel), -1.0, 1.0); else - eimicSpeedCtrl = std::clamp(0.5 * (SpeedCtrlValue * 2 - Vel), -1.0, 1.0); + eimicSpeedCtrlValue = std::clamp(0.5 * (SpeedCtrlValue * 2 - Vel), -1.0, 1.0); } if ((SpeedCtrlAutoTurnOffFlag & 2) == 2 && brakes.distributor->GetEDBCP() > 0.25) { @@ -1292,7 +1292,7 @@ void physics::Vehicle::CheckSpeedCtrl(double dt) } else { - eimicSpeedCtrl = 1; + eimicSpeedCtrlValue = 1; eimicSpeedCtrlIntegral = 0; SpeedCtrlUnit.Parking = false; SendCtrlToNext(VehicleCommand::speedControlParking, SpeedCtrlUnit.Parking, CabActive); @@ -1311,7 +1311,7 @@ void physics::Vehicle::SpeedCtrlRegulator(double dt, double const accfactor) 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; + SpeedCtrlUnit.BrakeInterventionBraking = eSCP < -1.1 && retarder_not_work && eimicSpeedCtrlValue < -0.99 * SpeedCtrlUnit.DesiredPower; eSCP = -1.0; } SpeedCtrlUnit.BrakeInterventionUnbraking = eSCP > 0.0 || Vel == 0.0; @@ -1327,14 +1327,14 @@ void physics::Vehicle::SpeedCtrlRegulator(double dt, double const accfactor) eimicSpeedCtrlIntegral = 0; } auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; - eimicSpeedCtrl = safe_clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); + eimicSpeedCtrlValue = safe_clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrlValue - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrlValue + SpeedCtrlUnit.PowerUpSpeed * dt); if (Vel < SpeedCtrlUnit.FullPowerVelocity) { - eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); + eimicSpeedCtrlValue = std::min(eimicSpeedCtrlValue, SpeedCtrlUnit.InitialPower); } if (Vel < SpeedCtrlUnit.StartVelocity && mainCtrlPos < MainCtrlPosNo) { - eimicSpeedCtrl = 0; + eimicSpeedCtrlValue = 0; eimic = 0; } } @@ -1342,7 +1342,7 @@ void physics::Vehicle::SpeedCtrlRegulator(double dt, double const accfactor) bool physics::Vehicle::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); + return speedCtrl && (scndCtrlPosNo == 0 || EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric); } bool physics::Vehicle::IsSpeedCtrlEngaged() const @@ -1379,7 +1379,7 @@ bool physics::Vehicle::SpeedCtrlSwitch(bool const State) void physics::Vehicle::SpeedCtrlButton(int button) { - if (SpeedCtrl && IsSpeedCtrlEngaged()) + if (speedCtrl && IsSpeedCtrlEngaged()) { SpeedCtrlValue = SpeedCtrlButtons[button]; } @@ -1387,7 +1387,7 @@ void physics::Vehicle::SpeedCtrlButton(int button) void physics::Vehicle::SpeedCtrlInc() { - if (SpeedCtrl && IsSpeedCtrlEngaged()) + if (speedCtrl && IsSpeedCtrlEngaged()) { double x = floor(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) + 1.0; SpeedCtrlValue = std::min(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MaxVelocity); @@ -1396,7 +1396,7 @@ void physics::Vehicle::SpeedCtrlInc() void physics::Vehicle::SpeedCtrlDec() { - if (SpeedCtrl && IsSpeedCtrlEngaged()) + if (speedCtrl && IsSpeedCtrlEngaged()) { double x = ceil(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) - 1.0; SpeedCtrlValue = std::max(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MinVelocity); @@ -1405,7 +1405,7 @@ void physics::Vehicle::SpeedCtrlDec() bool physics::Vehicle::SpeedCtrlPowerInc() { - if (!(SpeedCtrl && IsSpeedCtrlEngaged())) + if (!(speedCtrl && IsSpeedCtrlEngaged())) return false; if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MaxPower) @@ -1417,7 +1417,7 @@ bool physics::Vehicle::SpeedCtrlPowerInc() bool physics::Vehicle::SpeedCtrlPowerDec() { - if (!(SpeedCtrl && IsSpeedCtrlEngaged())) + if (!(speedCtrl && IsSpeedCtrlEngaged())) return false; if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MinPower) diff --git a/physics/components/couplers.cpp b/physics/components/couplers.cpp index dd0e300e6..2ee5f8ec3 100644 --- a/physics/components/couplers.cpp +++ b/physics/components/couplers.cpp @@ -448,7 +448,7 @@ void physics::Vehicle::automatic_coupling(VehicleEnd const End, physics::Vehicle auto const safe{AutomaticCouplingSafe(End, Other, OtherEnd)}; auto const caught{safe && Attach(End, OtherEnd, &Other, couplingtype)}; // HACK: we're reusing sound enum to mark whether vehicle was connected to another - AIFlag |= (caught ? sound::attachcoupler : 0); + aiFlag |= (caught ? sound::attachcoupler : 0); // coupled, or locked until the vehicles part, so they don't couple as soon as the collision slows them down thiscoupler.AutomaticCouplingAllowed = safe && false == caught; othercoupler.AutomaticCouplingAllowed = safe && false == caught; @@ -565,7 +565,7 @@ bool physics::Vehicle::coupler_stop_hit(VehicleEnd const End, physics::Vehicle & { return true; } - auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, TotalMass, Other.TotalMass)}; + auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, totalMass, Other.totalMass)}; // the other vehicle keeps the state of the pair alike othercoupler.physics_state.elongation = state.elongation; // with physics.collisions new the crush of the ends past the buffers is crush_hit()'s diff --git a/physics/components/diesel.cpp b/physics/components/diesel.cpp index 4ebbc65bd..71014515d 100644 --- a/physics/components/diesel.cpp +++ b/physics/components/diesel.cpp @@ -226,16 +226,16 @@ bool physics::Vehicle::WaterCircuitsLinkSwitch(bool State, range_t const Notify) return false; } - bool const initialstate{WaterCircuitsLink}; + bool const initialstate{waterCircuitsLink}; - WaterCircuitsLink = State; + waterCircuitsLink = State; if (Notify != range_t::local) { - SendCtrlToNext(VehicleCommand::waterCircuitsLinkSwitch, WaterCircuitsLink ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + SendCtrlToNext(VehicleCommand::waterCircuitsLinkSwitch, waterCircuitsLink ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return WaterCircuitsLink != initialstate; + return waterCircuitsLink != initialstate; } // fuel pump state toggle @@ -355,10 +355,10 @@ void physics::Vehicle::DieselEngineTractionForce(double dt, double const dmoment { Mw = dmoment * dtrans * Transmision.Efficiency; // dmoment i dtrans policzone przy okazji enginerotation if (retarder.present && retarder.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; + Mw -= dizel_MomentumRetarder(nrotValue * 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() @@ -366,7 +366,7 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) { double PosRatio; // tmpV:=V*CabActive*DirActive; - auto const tmpV{nrot * Pirazy2 * 0.5 * WheelDiameter * DirAbsolute}; //*CabActive*DirActive; + auto const tmpV{nrotValue * Pirazy2 * 0.5 * wheelDiameter * DirAbsolute}; //*CabActive*DirActive; auto tempUmax = 0.0; auto tempImax = 0.0; // jazda manewrowa @@ -400,19 +400,19 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) // stosunek mocy teraz do mocy max // NOTE: Mains in this context is working diesel engine if (true == lineContactors.IsClosed()) - Ft = DieselElectricForce(tmpV, power, PosRatio, tmp); + ft = DieselElectricForce(tmpV, power, PosRatio, tmp); else - Ft = 0; // jak nastawnik na zero, to sila tez zero + ft = 0; // jak nastawnik na zero, to sila tez zero PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; } if (FuseFlag) - Ft = 0; + 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 + 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); @@ -432,12 +432,12 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) EngineVoltage = 0; // przekazniki bocznikowania, kazdy inny dla kazdej pozycji - if (auto const fieldshuntingcontrol{fieldshunting::diesel_electric(AutoRelayType, FieldShuntSwitch, AutoRelayFlag)}; + if (auto const fieldshuntingcontrol{fieldshunting::diesel_electric(autoRelayType, fieldShuntSwitch, autoRelayFlag)}; false == lineContactors.IsClosed() || ShuntMode || fieldshuntingcontrol == fieldshunting::control::off) { scndCtrlPos = 0; } - else if (AutoRelayFlag) + else if (autoRelayFlag) { // the shunting relays set the field shunting (fieldshunting::control::automatic) ShuntFieldRelaysCheck(tmpV, PosRatio, tmp); @@ -454,12 +454,12 @@ void physics::Vehicle::DieselElectricShuntForce(double const tmpV, double &tmp) // 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); + ft = tmp * 1000.0 / (abs(tmpV) + 1.6); } else { EngineVoltage = 0; - Ft = 0; + ft = 0; } } @@ -473,9 +473,9 @@ double physics::Vehicle::DieselElectricDigitalForce(double const tmpV, double &t tempUmax = DElist[MainCtrlPosNo].Umax * std::min(eimic_positive, rpmratio); auto const tempPmax = DElist[MainCtrlPosNo].GenPower * std::min(eimic_positive, rpmratio); if (true == lineContactors.IsClosed()) - Ft = DieselElectricForce(tmpV, tempPmax, eimic_positive, tempPmax); + ft = DieselElectricForce(tmpV, tempPmax, eimic_positive, tempPmax); else - Ft = 0; // jak nastawnik na zero, to sila tez zero + ft = 0; // jak nastawnik na zero, to sila tez zero return tempPmax; } @@ -504,7 +504,7 @@ void physics::Vehicle::DieselElectricShuntPower(double const tmp) } if (EnginePower < tmp) { - Ft *= EnginePower / tmp; + ft *= EnginePower / tmp; } } @@ -513,7 +513,7 @@ void physics::Vehicle::DieselElectricGenerator(double const tmp, double const te { if (abs(Im) > tempImax) { // nie ma nadmiarowego, tylko Imax i zwarcie na pradnicy - Ft = Ft / Im * tempImax; + ft = ft / Im * tempImax; Im = tempImax; } @@ -547,8 +547,8 @@ void physics::Vehicle::DieselElectricGenerator(double const tmp, double const te // power curve drop // NOTE: disabled for the time being due to side-effects if( ( tmpV > 1 ) && ( EnginePower < tmp ) ) { - Ft = std::lerp( - Ft, EnginePower / tmp, + ft = std::lerp( + ft, EnginePower / tmp, std::clamp( tmpV - 1.0, 0.0, 1.0 ) ); } */ @@ -559,9 +559,9 @@ double physics::Vehicle::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); + return nPoweredAxles * abs(abs(Moment) / motor_param(scndCtrlPos).mfi + motor_param(scndCtrlPos).mIsat); else - return NPoweredAxles * sqrt(abs(Moment * motor_param(scndCtrlPos).Isat)); + 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 @@ -609,7 +609,7 @@ void physics::Vehicle::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 (lineBreaker.IsClosed() && DirActive != 0 && false == FuseFlag && false == SlippingWheels && nopower) + if (lineBreaker.IsClosed() && DirActive != 0 && false == FuseFlag && false == slippingWheels && nopower) { brake.level += std::clamp(dieselelectric_dynamic_brake_demand() - brake.level, -brake.rate * dt, brake.rate * dt); } @@ -632,10 +632,10 @@ void physics::Vehicle::update_dieselelectric_dynamic_brake(double const dt) // would turn round each time the speed crosses zero, and in FTrain it never lets the stop of ComputeMovement() catch it void physics::Vehicle::apply_dieselelectric_dynamic_brake(double const dt) { - auto const force{dt > 0.0 ? std::min(DEDynamicBrake.force, TotalMass * std::abs(travelSpeed) / dt) : DEDynamicBrake.force}; - Ft = travelSpeed > 0.0 ? -force : travelSpeed < 0.0 ? force : 0.0; - Fw = Ft / NPoweredAxles; - Mw = Fw * WheelDiameter / 2.0; + auto const force{dt > 0.0 ? std::min(DEDynamicBrake.force, totalMass * std::abs(travelSpeed) / dt) : DEDynamicBrake.force}; + ft = travelSpeed > 0.0 ? -force : travelSpeed < 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; @@ -754,7 +754,7 @@ bool physics::Vehicle::dizel_GearShiftRequest(double const VelUp, double const V if (Vel > VelUp) { // shift up - if (ScndCtrlActualPos < ScndCtrlPosNo) + if (ScndCtrlActualPos < scndCtrlPosNo) { diesel.automaticGearShift = 1; OK = true; @@ -786,7 +786,7 @@ void physics::Vehicle::dizel_ClutchCheck() dizel_EngageSwitch(0.0); if (!(motor_param(ScndCtrlActualPos).mIsat > 0)) dizel_EngageSwitch(0.0); // wylacz sprzeglo na pozycjach neutralnych - if (!AutoRelayFlag) + if (!autoRelayFlag) ScndCtrlActualPos = scndCtrlPos; } @@ -899,7 +899,7 @@ bool physics::Vehicle::dizel_Update(double dt) diesel.ignitionRequested = true; } - if (true == diesel.ignitionRequested && LastSwitchingTime >= InitialCtrlDelay) + if (true == diesel.ignitionRequested && LastSwitchingTime >= initialCtrlDelay) { diesel.startupRequested = false; @@ -951,7 +951,7 @@ double physics::Vehicle::dizel_fillcheck(int mcp, double dt) if (true == lineBreaker.IsClosed() && MainCtrlPosNo > 0 && true == FuelPump.is_active) { - if (true == diesel.ignitionRequested && LastSwitchingTime >= 0.9 * InitialCtrlDelay) + if (true == diesel.ignitionRequested && LastSwitchingTime >= 0.9 * initialCtrlDelay) { // wzbogacenie przy rozruchu // NOTE: ignition flag is reset before this code is executed @@ -1106,7 +1106,7 @@ double physics::Vehicle::dizel_Momentum(double Fill, double n, double dt) { Moment = -diesel.standingMoment; } - if (enrot < diesel.minRevolutions / 10.0 && eAngle < M_PI_2) + if (enrot < diesel.minRevolutions / 10.0 && eAngleValue < M_PI_2) { // wstrzymywanie przy malych obrotach Moment -= diesel.standingMoment; @@ -1410,7 +1410,7 @@ void physics::Vehicle::dizel_Heat(double const dt) auto const kf2{kurek07 * (diesel.heat.kw * (0.3 + 0.7 * zaluzje2) * diesel.heat.rpmw2 + diesel.heat.kv * (0.3 + 0.7 * zaluzje2) * Vel / 3.6) + 2}; auto const dTs2{diesel.heat.kfo2 * (diesel.heat.To - diesel.heat.Tsr2) / (gw2 * Cw)}; // przy otwartym kurku B ma³y obieg jest dogrzewany przez du¿y - stosujemy przy korzystaniu z podgrzewacza oraz w zimie - auto const Qch2{-kf2 * (diesel.heat.Tsr2 - diesel.heat.Te) + 80 * (true == WaterCircuitsLink ? 1 : 0) * (diesel.heat.Twy - diesel.heat.Tsr2)}; + auto const Qch2{-kf2 * (diesel.heat.Tsr2 - diesel.heat.Te) + 80 * (true == waterCircuitsLink ? 1 : 0) * (diesel.heat.Twy - diesel.heat.Tsr2)}; auto const dTch2{Qch2 / (gw2 * Cw)}; // auxiliary water circuit heat transfers finalization // NOTE: since primary circuit doesn't read data from the auxiliary one, we can pretty safely finalize auxiliary updates before touching the primary circuit diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index b160d57b0..62543c048 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -68,7 +68,7 @@ double TractionDrive::EngineMaxRpm(physics::Vehicle const & /*vehicle*/) const double TractionDrive::UpdateEngineRevolutions(physics::Vehicle &vehicle, double /*dt*/, double & /*transmission*/, double & /*moment*/) const { - vehicle.enrot = vehicle.Transmision.Ratio * vehicle.nrot; + vehicle.enrot = vehicle.Transmision.Ratio * vehicle.nrot(); return 0.0; } @@ -189,7 +189,7 @@ class DumbDrive final : public TractionDrive public: double UpdateEnginePower(physics::Vehicle &vehicle) const override { - auto const posRatio{(vehicle.MainCtrlPos() + vehicle.ScndCtrlPos()) / (vehicle.MainCtrlPosNo + vehicle.ScndCtrlPosNo + 0.01)}; + auto const posRatio{(vehicle.MainCtrlPos() + vehicle.ScndCtrlPos()) / (vehicle.MainCtrlPosNo + vehicle.ScndCtrlPosNo() + 0.01)}; vehicle.EnginePower = /*1000.0 **/ vehicle.Power * posRatio; return posRatio; } @@ -273,7 +273,7 @@ public: // wywalanie szybkiego z powodu niewłaściwego napięcia // (a line breaker closed ahead of the pantographs holds without voltage) if (true == vehicle.lineBreaker.IsClosed() && ((false == vehicle.protection.UndervoltageHolds() && false == vehicle.lineBreaker.config.pantographsRequireIt) || false == vehicle.protection.OvervoltageHolds()) && - vehicle.MainSwitch(false, vehicle.TrainType == train_type::emu ? range_t::unit : range_t::local)) // TODO: check whether we need to send this EMU-wide + vehicle.MainSwitch(false, vehicle.TrainType() == train_type::emu ? range_t::unit : range_t::local)) // TODO: check whether we need to send this EMU-wide { vehicle.RaiseEventFlag(); } @@ -321,9 +321,9 @@ public: switch (ammeter) { // do asynchronicznych case 1: - return vehicle.WindingRes * vehicle.Mm / vehicle.Vadd; + return vehicle.WindingRes() * vehicle.Mm / vehicle.Vadd; case 2: - return vehicle.inductionMotor.forceShare * vehicle.WindingRes; + return vehicle.inductionMotor.forceShare * vehicle.WindingRes(); default: return vehicle.ShowCurrentP(ammeter); } @@ -341,7 +341,7 @@ public: if (vehicle.lineBreaker.IsClosed() && ((vehicle.TractionSupplyVoltage() < vehicle.TractionSupplyMinVoltage() && false == vehicle.lineBreaker.config.pantographsRequireIt) || vehicle.TractionSupplyVoltage() > vehicle.EnginePowerSource.CollectorParameters.MaxV + 200)) { - vehicle.MainSwitch(false, vehicle.TrainType == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide + vehicle.MainSwitch(false, vehicle.TrainType() == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide } } }; @@ -372,7 +372,7 @@ public: else transmission = vehicle.Transmision.Ratio * vehicle.motor_param(vehicle.ScndCtrlActualPos).mIsat; - moment = vehicle.dizel_Momentum(vehicle.diesel.fill, transmission * vehicle.nrot * vehicle.DirActive, dt); // oblicza tez enrot + moment = vehicle.dizel_Momentum(vehicle.diesel.fill, transmission * vehicle.nrot() * vehicle.DirActive, dt); // oblicza tez enrot return 0.0; } bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp index ec185a5a8..97d17fab5 100644 --- a/physics/components/electrics.cpp +++ b/physics/components/electrics.cpp @@ -48,7 +48,7 @@ physics::PantographAirSupply physics::Vehicle::PantographAirSupplyNow() const supply.lowVoltage = lowVoltage.IsAvailable(); // tylko jeśli pantografujący supply.collectors = EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0; - supply.multipleUnit = TrainType == train_type::emu; + supply.multipleUnit = trainType == train_type::emu; supply.mainReservoirPressure = mainPipe.Pressure(); supply.controlReservoirPressure = brakes.controlReservoirPressure; supply.maxPressure = EnginePowerSource.CollectorParameters.MaxPress; @@ -71,14 +71,14 @@ void physics::Vehicle::PantPressureSwitchCheck() void physics::Vehicle::PantPressureSwitchTrip() { // opuszczenie pantografów przy niskim ciśnieniu - if (TrainType != train_type::emu) + if (trainType != train_type::emu) { // 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 == train_type::emu ? range_t::unit : range_t::local); + MainSwitch(false, trainType == train_type::emu ? range_t::unit : range_t::local); } } else @@ -251,7 +251,7 @@ void physics::Vehicle::MainsCheck(double const Deltatime) // an emergency brake application made under power opens the line breaker, where the vehicle has such an interlock if (lineBreaker.IsClosed() && EmergencyBrakeHoldsMainOff()) { - MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local); + MainSwitch(false, trainType == train_type::emu ? range_t::unit : range_t::local); } } @@ -722,7 +722,7 @@ void physics::Vehicle::LightsCheck(double const /*Timestep*/) bool physics::Vehicle::BatterySwitch(bool State, range_t const Notify) { using enum range_t; - if (PulleeMode && State) + if (pulleeMode && State) { // the battery of a vehicle prepared for hauling stays off return false; diff --git a/physics/components/fizparser.cpp b/physics/components/fizparser.cpp index d4dbda73a..a3819786f 100644 --- a/physics/components/fizparser.cpp +++ b/physics/components/fizparser.cpp @@ -754,7 +754,7 @@ bool physics::Vehicle::LoadFIZ_Parse(cParser &fizparser) // the DefaultPos of a short or an empty DimmerList would put the dimmer outside of it modernDimmerDefaultPosition = clampDimmerPosition(modernDimmerDefaultPosition); modernDimmerPosition = clampDimmerPosition(modernDimmerPosition); - if (!enableModernDimmer) + if (!enableModernDimmerValue) { modernDimmerPosition = modernDimmerDefaultPosition; } @@ -1008,7 +1008,7 @@ bool physics::Vehicle::LoadFIZ_Section(std::string const &inputline, std::mapsecond : train_type::generic; + trainType = lookup != types.end() ? lookup->second : train_type::generic; } - if (TrainType == train_type::emu) + if (trainType == train_type::emu) { IminLo = 1; IminHi = 2; - Imin = 1; + imin = 1; } } @@ -176,23 +176,23 @@ void physics::Vehicle::LoadFIZ_Dimensions(std::string const &line) void physics::Vehicle::LoadFIZ_Wheels(std::string const &line) { - extract_value(WheelDiameter, "D", line, ""); - WheelDiameterL = WheelDiameter; // gdyby nie było parametru, lepsze to niż zero + extract_value(wheelDiameter, "D", line, ""); + WheelDiameterL = wheelDiameter; // gdyby nie było parametru, lepsze to niż zero extract_value(WheelDiameterL, "Dl", line, ""); - WheelDiameterT = WheelDiameter; // gdyby nie było parametru, lepsze to niż zero + WheelDiameterT = wheelDiameter; // gdyby nie było parametru, lepsze to niż zero extract_value(WheelDiameterT, "Dt", line, ""); extract_value(TrackW, "Tw", line, ""); extract_value(AxleInertialMoment, "AIM", line, ""); extract_value(AxleArangement, "Axle", line, ""); - NPoweredAxles = s2NPW(AxleArangement); - NAxles = NPoweredAxles + s2NNW(AxleArangement); + nPoweredAxles = s2NPW(AxleArangement); + nAxles = nPoweredAxles + s2NNW(AxleArangement); BearingType = extract_value("BearingType", line) == "Roll" ? 1 : 0; - extract_value(ADist, "Ad", line, ""); - extract_value(BDist, "Bd", line, ""); + extract_value(aDist, "Ad", line, ""); + extract_value(bDist, "Bd", line, ""); if (AxleInertialMoment <= 0.0) { @@ -201,8 +201,8 @@ void physics::Vehicle::LoadFIZ_Wheels(std::string const &line) */ // approximation formula by youby auto const k = 472.0; // arbitrary constant - AxleInertialMoment = k / 4.0 * std::pow(WheelDiameter, 4.0) * NAxles; - Mred = k * std::pow(WheelDiameter, 2.0) * NAxles; + AxleInertialMoment = k / 4.0 * std::pow(wheelDiameter, 4.0) * nAxles; + mred = k * std::pow(wheelDiameter, 2.0) * nAxles; } } @@ -435,7 +435,7 @@ void physics::Vehicle::LoadFIZ_Doors(std::string const &line) extract_value(MirrorVelClose, "MirrorVelClose", line, ""); extract_value(DoorsOpenWithPermitAfter, "DoorOpenWithPermit", line, ""); - extract_value(DoorsPermitLightBlinking, "DoorsPermitLightBlinking", line, ""); + extract_value(doorsPermitLightBlinking, "DoorsPermitLightBlinking", line, ""); } namespace { @@ -805,9 +805,9 @@ void physics::Vehicle::LoadFIZ_CntrlControllers(std::string const &line) using enum horn_supply; std::map> const hornsupplies{{"Pneumatic", air}, {"Electric", electric}}; auto lookup = hornsupplies.find(extract_value("HornType", line)); - HornSupply = lookup != hornsupplies.end() ? lookup->second : air; + hornSupply = lookup != hornsupplies.end() ? lookup->second : air; lookup = hornsupplies.find(extract_value("Horn3Type", line)); - Horn3Supply = lookup != hornsupplies.end() ? lookup->second : HornSupply; + Horn3Supply = lookup != hornsupplies.end() ? lookup->second : hornSupply; } // dynamicbrake @@ -831,25 +831,25 @@ void physics::Vehicle::LoadFIZ_CntrlControllers(std::string const &line) } extract_value(MainCtrlPosNo, "MCPN", line, ""); - extract_value(ScndCtrlPosNo, "SCPN", line, ""); + extract_value(scndCtrlPosNo, "SCPN", line, ""); extract_value(ScndInMain, "SCIM", line, ""); - extract_value(MainCtrlMaxDirChangePos, "DirChangeMaxPos", line, ""); + extract_value(mainCtrlMaxDirChangePos, "DirChangeMaxPos", line, ""); if (auto const autorelay{ToLower(extract_value("AutoRelay", line))}; autorelay == "optional") { - AutoRelayType = 2; + autoRelayType = 2; } else if (autorelay == "yes") { - AutoRelayType = 1; + autoRelayType = 1; } else { - AutoRelayType = 0; + 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(fieldShuntSwitch, "FieldShuntSwitch", line, ""); extract_value(CoupledCtrl, "CoupledCtrl", line, ""); extract_value(HasCamshaft, "Camshaft", line, ""); @@ -857,22 +857,22 @@ void physics::Vehicle::LoadFIZ_CntrlControllers(std::string const &line) EIMCtrlType = std::clamp(EIMCtrlType, 0, 3); extract_value(brakes.config.independentTraxx, "LocalBrakeTraxx", line, ""); extract_value(EIMCtrlAdditionalZeros, "EIMCtrlAddZeros", line, ""); - extract_value(EIMCtrlEmergency, "EIMCtrlEmergency", line, ""); + extract_value(eimCtrlEmergency, "EIMCtrlEmergency", line, ""); // Elf (EIMCtrlType 2): an emergency brake position below the controller's position 0, which shifts the other positions up by one - extract_value(EIMCtrlMainEmergency, "EIMCtrlMainEmergency", line, ""); + extract_value(eimCtrlMainEmergency, "EIMCtrlMainEmergency", line, ""); if (auto const elfpositions{4 + EIMCtrlEmergencyPositions()}; EIMCtrlEmergencyPositions() > 0 && MainCtrlPosNo < elfpositions) { // the old positions in the file: without the fix-up the controller would have no power position, and the // reverser would stop working at neutral (DirChangeMaxPos read before, in the old positions) - MainCtrlMaxDirChangePos += EIMCtrlEmergencyPositions(); - ErrorLog(std::format("Bad fiz: EIMCtrlMainEmergency needs MCPN={} in {}, DirChangeMaxPos taken as {}", elfpositions, TypeName, MainCtrlMaxDirChangePos)); + mainCtrlMaxDirChangePos += EIMCtrlEmergencyPositions(); + ErrorLog(std::format("Bad fiz: EIMCtrlMainEmergency needs MCPN={} in {}, DirChangeMaxPos taken as {}", elfpositions, TypeName, mainCtrlMaxDirChangePos)); MainCtrlPosNo = elfpositions; } extract_value(ScndS, "ScndS", line, ""); // brak pozycji rownoleglej przy niskiej nastawie PSR extract_value(ScndCtrlResistiveLock, "ScndCtrlResistiveLock", line, ""); // bocznikowanie tylko na pozycjach bezoporowych - extract_value(InitialCtrlDelay, "IniCDelay", line, ""); + extract_value(initialCtrlDelay, "IniCDelay", line, ""); extract_value(CtrlDelay, "SCDelay", line, ""); CtrlDownDelay = CtrlDelay; // hunter-101012: jesli nie ma SCDDelay; extract_value(CtrlDownDelay, "SCDDelay", line, ""); @@ -929,7 +929,7 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) this->converter.config.start = lookup != starts.end() ? lookup->second : manual; } extract_value(this->converter.config.startDelay, "ConverterStartDelay", line, ""); - extract_value(this->converter.config.overloadRelayOffWithLineBreaker, "ConverterOverloadWhenMainIsOff", line, TrainType == train_type::emu ? "yes" : "no"); + extract_value(this->converter.config.overloadRelayOffWithLineBreaker, "ConverterOverloadWhenMainIsOff", line, trainType == train_type::emu ? "yes" : "no"); // compressor { auto lookup = starts.find(extract_value("CompressorStart", line)); @@ -941,7 +941,7 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) pantographAir.config.compressorStart = lookup != starts.end() ? lookup->second : manual; } // pantograph compressor valve - pantographAir.config.autoValve = TrainType == train_type::emu; // legacy code behaviour, automatic valve was initially installed in all EMUs + pantographAir.config.autoValve = trainType == train_type::emu; // legacy code behaviour, automatic valve was initially installed in all EMUs extract_value(pantographAir.config.autoValve, "PantAutoValve", line, ""); // pantographs valve { @@ -1006,14 +1006,14 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) // ground relay { auto lookup = starts.find(extract_value("GroundRelayStart", line)); - auto const defaultstart{TrainType == train_type::emu ? automatic : manual}; + auto const defaultstart{trainType == train_type::emu ? automatic : manual}; protection.config.groundStart = 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 == train_type::emu ? converter : manual}; + auto const defaultstart{trainType == train_type::emu ? converter : manual}; this->converter.config.overloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart; } } @@ -1021,9 +1021,9 @@ void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) void physics::Vehicle::LoadFIZ_Blending(std::string const &line) { - extract_value(brakes.blending.maxSpeed, "MED_Vmax", line, std::to_string(Vmax)); + extract_value(brakes.blending.maxSpeed, "MED_Vmax", line, std::to_string(vmax)); extract_value(brakes.blending.minSpeed, "MED_Vmin", line, "0"); - extract_value(brakes.blending.referenceSpeed, "MED_Vref", line, std::to_string(Vmax)); + extract_value(brakes.blending.referenceSpeed, "MED_Vref", line, std::to_string(vmax)); extract_value(brakes.blending.maxDeceleration, "MED_amax", line, "9.81"); extract_value(brakes.blending.epCorrection, "MED_EPVC", line, ""); extract_value(brakes.blending.loadCorrection, "MED_Ncor", line, ""); @@ -1144,11 +1144,11 @@ void physics::Vehicle::LoadFIZ_Genset(std::string const &Line) void physics::Vehicle::LoadFIZ_SpeedControl(std::string const &Line) { // speed control - extract_value(SpeedCtrl, "SpeedCtrl", Line, ""); - if (!SpeedCtrl && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo > 0) // backward compatibility - SpeedCtrl = true; + extract_value(speedCtrl, "SpeedCtrl", Line, ""); + if (!speedCtrl && EngineType == TEngineType::ElectricInductionMotor && scndCtrlPosNo > 0) // backward compatibility + speedCtrl = true; extract_value(SpeedCtrlDelay, "SpeedCtrlDelay", Line, ""); - SpeedCtrlTypeTime = extract_value("SpeedCtrlType", Line) == "Time" ? true : false; + speedCtrlTypeTime = extract_value("SpeedCtrlType", Line) == "Time" ? true : false; extract_value(SpeedCtrlAutoTurnOffFlag, "SpeedCtrlATOF", Line, ""); auto speedpresets = Split(extract_value("SpeedButtons", Line), '|'); @@ -1213,11 +1213,11 @@ void physics::Vehicle::LoadFIZ_Engine(std::string const &Input) { extract_value(NominalVoltage, "Volt", Input, ""); - extract_value(WindingRes, "WindingRes", Input, ""); - if (WindingRes == 0.0) + extract_value(windingRes, "WindingRes", Input, ""); + if (windingRes == 0.0) { - WindingRes = 0.01; + windingRes = 0.01; } extract_value(nmax, "nmax", Input, ""); nmax /= 60.0; @@ -1263,7 +1263,7 @@ void physics::Vehicle::LoadFIZ_Engine(std::string const &Input) extract_value(MotorBlowers[VehicleEnd::front].min_start_velocity, "MotorBlowersStartVelocity", Input, ""); MotorBlowers[VehicleEnd::rear] = MotorBlowers[VehicleEnd::front]; // pressure switch - extract_value(protection.config.hasPressureSwitch, "PressureSwitch", Input, TrainType != train_type::emu ? "yes" : "no"); + extract_value(protection.config.hasPressureSwitch, "PressureSwitch", Input, trainType != train_type::emu ? "yes" : "no"); // its brake cylinder half; the brake pipe one stays extract_value(protection.config.pressureSwitchWatchesCylinders, "PressureSwitchBrakeCylinder", Input, ""); } @@ -1366,8 +1366,8 @@ void physics::Vehicle::LoadFIZ_EngineDieselElectric(std::string const &Input) ShuntModeAllow = true; ShuntMode = false; anPos = 0.0; - ImaxHi = 2; - ImaxLo = 1; + imaxHi = 2; + imaxLo = 1; } extract_value(trainHeating.config.engineRpm, "HeatingRPM", Input, ""); extract_value(diesel.shaftInertia, "AIM", Input, "1.25"); @@ -1481,7 +1481,7 @@ void physics::Vehicle::LoadFIZ_Switches(std::string const &Input) extract_value(UniversalResetButtonFlag[0], "RelayResetButton1", Input, ""); extract_value(UniversalResetButtonFlag[1], "RelayResetButton2", Input, ""); extract_value(UniversalResetButtonFlag[2], "RelayResetButton3", Input, ""); - extract_value(enableModernDimmer, "ModernDimmer", Input, ""); + extract_value(enableModernDimmerValue, "ModernDimmer", Input, ""); // pantograph presets { auto &presets{pantographCircuit.presets.first}; @@ -1518,10 +1518,10 @@ void physics::Vehicle::LoadFIZ_Circuit(std::string const &Input) extract_value(CircuitRes, "CircuitRes", Input, ""); extract_value(IminLo, "IminLo", Input, ""); extract_value(IminHi, "IminHi", Input, ""); - extract_value(ImaxLo, "ImaxLo", Input, ""); - extract_value(ImaxHi, "ImaxHi", Input, ""); - Imin = IminLo; - Imax = ImaxLo; + extract_value(imaxLo, "ImaxLo", Input, ""); + extract_value(imaxHi, "ImaxHi", Input, ""); + imin = IminLo; + Imax = imaxLo; extract_value(TUHEX_Sum, "TUHEX_Sum", Input, ""); extract_value(TUHEX_Diff, "TUHEX_Diff", Input, ""); extract_value(TUHEX_MaxIw, "TUHEX_MaxIw", Input, ""); @@ -1535,10 +1535,10 @@ void physics::Vehicle::LoadFIZ_Circuit(std::string const &Input) void physics::Vehicle::LoadFIZ_AI(std::string const &Input) { - extract_value(AIHintPantstate, "Pantstate", Input, ""); - extract_value(AIHintShuntPantstate, "ShuntPantstate", Input, ""); + extract_value(aiHintPantstate, "Pantstate", Input, ""); + extract_value(aiHintShuntPantstate, "ShuntPantstate", Input, ""); extract_value(AIHintPantUpIfIdle, "IdlePantUp", Input, ""); - extract_value(AIHintLocalBrakeAccFactor, "LocalBrakeAccFactor", Input, ""); + extract_value(aiHintLocalBrakeAccFactor, "LocalBrakeAccFactor", Input, ""); } void physics::Vehicle::LoadFIZ_RList(std::string const &Input) @@ -1605,10 +1605,10 @@ void physics::Vehicle::LoadFIZ_UCList(std::string const &Input) extract_value(UniCtrlListSize, "Size", Input, ""); extract_value(UniCtrlIntegratedBrakeCtrl, "IntegratedBrake", Input, ""); - extract_value(UniCtrlIntegratedLocalBrakeCtrl, "IntegratedLocBrake", Input, ""); + extract_value(uniCtrlIntegratedLocalBrakeCtrl, "IntegratedLocBrake", Input, ""); extract_value(UniCtrlIntegratedBrakePNCtrl, "IntegratedBrakePN", Input, ""); - extract_value(UniCtrlValStep, "CtrlValStep", Input, ""); - UniCtrlValStep = std::max(UniCtrlValStep, 0.0); + extract_value(uniCtrlValStep, "CtrlValStep", Input, ""); + uniCtrlValStep = std::max(uniCtrlValStep, 0.0); } void physics::Vehicle::LoadFIZ_DList(std::string const &Input) diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index f057e4cce..3103f7911 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -229,9 +229,9 @@ double physics::Vehicle::PipeRatio(void) const // ************************************************************************************************* bool physics::Vehicle::EpFuseSwitch(bool State) { - if (EpFuse != State) + if (epFuse != State) { - EpFuse = State; + epFuse = State; return true; } else @@ -588,7 +588,7 @@ bool physics::Vehicle::SwitchEPBrake(int state) bool physics::Vehicle::EPBrakeControlPowered() const { - return lowVoltage.Is24vAvailable() && DirActive != 0 && EpFuse; + return lowVoltage.Is24vAvailable() && DirActive != 0 && epFuse; } // ************************************************************************************************* @@ -600,7 +600,7 @@ bool physics::Vehicle::IncBrakePress(double &brake, double PressLimit, double dp bool IBP; // if (DynamicBrakeType<>dbrake_switch) and (DynamicBrakeType<>dbrake_none) and // ((BrakePress>2.0) or (PipePress<3.7{(LowPipePress+0.5)})) then - if (brakes.electrodynamic.type != dbrake_switch && brakes.electrodynamic.type != dbrake_none && brakes.cylinderPressure > 2.0 && TrainType != train_type::emu) // yB radzi nie sprawdzać ciśnienia w przewodzie + if (brakes.electrodynamic.type != dbrake_switch && brakes.electrodynamic.type != dbrake_none && brakes.cylinderPressure > 2.0 && trainType != train_type::emu) // yB radzi nie sprawdzać ciśnienia w przewodzie // hunter-301211: dla EN57 silnikow nie odlaczamy { brakes.electrodynamic.on = true; // uruchamianie hamulca ED albo odlaczanie silnikow @@ -861,7 +861,7 @@ void physics::Vehicle::UpdatePipePressure(double dt) brakePipe.SetCouplersPending(true); if (brakes.config.antiSlipType == 128) - brakes.distributor->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); + brakes.distributor->ASB(int(slippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); brakes.pipeFlow = 0; @@ -888,7 +888,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) if (EngineType != TEngineType::ElectricInductionMotor) { double lbpa = brakes.config.independentTraxx ? eim_localbrake : brakes.IndependentPosition(); - if (EIMCtrlType > 0 && UniCtrlIntegratedLocalBrakeCtrl) + if (EIMCtrlType > 0 && uniCtrlIntegratedLocalBrakeCtrl) { lbpa = std::max(0.0, -eimic_real); } @@ -896,7 +896,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) { lbpa = std::max(lbpa, brakes.holding.deceleration); } - brakes.independentValveFlow = brakes.independentValve->GetPF(PulleeMode ? 0.0 : std::max(lbpa, brakes.IndependentPositionEim()), brakes.distributor->GetBCP(), mainPipe.Pressure(), dt, 0); + brakes.independentValveFlow = brakes.independentValve->GetPF(pulleeMode ? 0.0 : std::max(lbpa, brakes.IndependentPositionEim()), brakes.distributor->GetBCP(), mainPipe.Pressure(), dt, 0); } else { @@ -917,7 +917,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) { lbpa = 0.0; } - brakes.independentValveFlow = brakes.independentValve->GetPF(PulleeMode ? 0.0 : std::max(lbpa, brakes.IndependentPositionEim()), brakes.distributor->GetBCP(), mainPipe.Pressure(), dt, 0); + brakes.independentValveFlow = brakes.independentValve->GetPF(pulleeMode ? 0.0 : std::max(lbpa, brakes.IndependentPositionEim()), brakes.distributor->GetBCP(), mainPipe.Pressure(), dt, 0); } } @@ -927,7 +927,7 @@ void physics::Vehicle::UpdateMainValve(double dt) auto const temp{MainValveSupply()}; brakes.driverValve->SetReductor(brakes.HandleCapPosition()); - if (PulleeMode) + if (pulleeMode) { // the driver's valve of a vehicle prepared for hauling is cut out, whatever its handle shows brakes.driverValveFlow = 0; @@ -967,7 +967,7 @@ double physics::Vehicle::MainValveSupply() brakes.pipeLock.locked = brakePipe.Pressure() < (brakes.pipeLock.locked ? brakes.pipeLock.offPressure : brakes.pipeLock.onPressure); bool lock_new = (brakes.pipeLock.locked && !brakes.pipeLock.unlockPressed && brakes.HandlePositionReal() > brakes.pipeLock.unlockHandlePosition) || (brakes.config.emergencyCutsOffDriverValve && brakes.emergencyValve.flow > 0); // new simple codition based on .fiz bool lock_old = brakes.config.driverValveType == TBrakeHandle::FV4a // old complex condition based on assumptions - && brakePipe.Pressure() < 2.75 && (brakes.distributor->GetStatus() & b_rls) == 0 && brakes.config.subsystem == TBrakeSubSystem::ss_LSt && TrainType != train_type::emu && !brakes.pipeLock.unlockPressed; + && brakePipe.Pressure() < 2.75 && (brakes.distributor->GetStatus() & b_rls) == 0 && brakes.config.subsystem == TBrakeSubSystem::ss_LSt && trainType != train_type::emu && !brakes.pipeLock.unlockPressed; if (lock_old || lock_new) { @@ -1002,10 +1002,10 @@ void physics::Vehicle::UpdateEmergencyValve(double dt) // 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 && brakes.IndependentPosition() >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || + auto const ownemergency{radioStopFlag || (eimCtrlEmergency && brakes.IndependentPosition() >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || (brakes.spring.driveEmergencySpeed >= 0 && Vel > brakes.spring.driveEmergencySpeed && brakes.spring.isActive) || (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)}; - if (brakes.alarmChain || (ownemergency && false == PulleeMode)) + if (brakes.alarmChain || (ownemergency && false == pulleeMode)) { brakes.emergencyValve.flow = PF(0, brakePipe.Pressure(), 0.15) * dt; } @@ -1034,7 +1034,7 @@ void physics::Vehicle::UpdateDistributorSettings() brakes.distributor->PLC(brakes.config.maxCylinderPressure[brakes.loadSetting]); else //(Hamulec as TWest).PLC(TotalMass); - brakes.distributor->PLC(TotalMass - Mred); + brakes.distributor->PLC(totalMass - mred); break; } @@ -1047,7 +1047,7 @@ void physics::Vehicle::UpdateDistributorSettings() for (auto const &couplerentry : Couplers) // nie podoba mi się to rozwiązanie, chyba trzeba // dodać jakiś wpis do fizyki na to - if (et41or42(TrainType) && couplerentry.Connected != nullptr && et41or42(couplerentry.Connected->TrainType) && couplerentry.CouplingFlag.HasAll(Coupling::control | Coupling::mainHose)) + if (et41or42(trainType) && couplerentry.Connected != nullptr && et41or42(couplerentry.Connected->trainType) && couplerentry.CouplingFlag.HasAll(Coupling::control | Coupling::mainHose)) brakes.independentCylinderPressure = std::max(couplerentry.Connected->brakes.independentValve->GetCP(), brakes.independentCylinderPressure); // if ((DynamicBrakeFlag) && (EngineType == ElectricInductionMotor)) @@ -1065,7 +1065,7 @@ void physics::Vehicle::UpdateDistributorSettings() if (brakes.config.maxPressureMass < 2) brakes.distributor->PLC(brakes.config.maxCylinderPressure[brakes.loadSetting]); else - brakes.distributor->PLC(TotalMass - Mred); + brakes.distributor->PLC(totalMass - mred); } break; } @@ -1081,7 +1081,7 @@ void physics::Vehicle::UpdateDistributorSettings() case TBrakeValve::EP2: case TBrakeValve::EP1: { - brakes.distributor->PLC(TotalMass - Mred); + brakes.distributor->PLC(totalMass - mred); break; } case TBrakeValve::ESt3AL2: @@ -1094,7 +1094,7 @@ void physics::Vehicle::UpdateDistributorSettings() brakes.distributor->PLC(brakes.config.maxCylinderPressure[brakes.loadSetting]); else //(Hamulec as TNESt3).PLC(TotalMass); - brakes.distributor->PLC(TotalMass - Mred); + brakes.distributor->PLC(totalMass - mred); brakes.independentCylinderPressure = brakes.independentValve->GetCP(); //(Hamulec as TNESt3).SetLBP(LocBrakePress); brakes.distributor->SetLBP(brakes.independentCylinderPressure); @@ -1110,7 +1110,7 @@ void physics::Vehicle::UpdateDistributorSettings() brakes.distributor->PLC(brakes.config.maxCylinderPressure[brakes.loadSetting]); else //(Hamulec as TKE).PLC(TotalMass); - brakes.distributor->PLC(TotalMass - Mred); + brakes.distributor->PLC(totalMass - mred); break; } default: @@ -1164,7 +1164,7 @@ void physics::Vehicle::UpdateScndPipePressure(double dt) mainPipe.reservoir->Flow(brakes.distributor->GetHPFlow(mainPipe.Pressure(), dt)); // NOTE: condition disabled to allow the air flow from the main hose to the main tank as well - if (/* ( ( Compressor > ScndPipePress ) && ( */ air.config.mainReservoirVolume > 0.0 /* ) ) || ( TrainType == train_type::emu ) || ( TrainType == train_type::dmu ) */) + if (/* ( ( Compressor > ScndPipePress ) && ( */ air.config.mainReservoirVolume > 0.0 /* ) ) || ( trainType == train_type::emu ) || ( trainType == train_type::dmu ) */) { double const dV = PF(air.MainReservoirPressure(), mainPipe.Pressure(), Spz) * dt; air.AddAir(dV / 1000.0); @@ -1234,7 +1234,7 @@ bool pipe_wakes(double const Flow, double const Pressure, TReservoir const &Rese // carry on past the pressure of the vehicle it comes from. so of one asleep, the pressure with what has flown in since double neighbour_pipe_pressure(physics::Vehicle const &Neighbour, double const Pressure, TReservoir const &Reservoir) { - if ((Global.physics_pipewake <= 0.f) || Neighbour.PhysicActivation) + if ((Global.physics_pipewake <= 0.f) || Neighbour.PhysicActivation()) return Pressure; return Reservoir.P_pending(); } diff --git a/physics/components/securitysystem.cpp b/physics/components/securitysystem.cpp index d922c51f2..3605d6810 100644 --- a/physics/components/securitysystem.cpp +++ b/physics/components/securitysystem.cpp @@ -205,7 +205,7 @@ bool TSecuritySystem::is_engine_blocked() const return velocity < AwareMinSpeed && pressed; } -void TSecuritySystem::load(std::string const &line, double Vmax) +void TSecuritySystem::load(std::string const &line, double vmax) { std::string awaresystem = extract_value("AwareSystem", line); if (awaresystem.find("Active") != std::string::npos) @@ -218,7 +218,7 @@ void TSecuritySystem::load(std::string const &line, double Vmax) separate_acknowledge = true; extract_value(AwareDelay, "AwareDelay", line, ""); - AwareMinSpeed = 0.1 * Vmax; // domyślnie 10% Vmax + AwareMinSpeed = 0.1 * vmax; // domyślnie 10% Vmax extract_value(AwareMinSpeed, "AwareMinSpeed", line, ""); extract_value(SoundSignalDelay, "SoundSignalDelay", line, ""); extract_value(EmergencyBrakeDelay, "EmergencyBrakeDelay", line, ""); diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index e2af68095..bd3f6b271 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -39,7 +39,7 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) WriteLog("check locomotive parameters..."); bool OK = true; - AutoRelayFlag = AutoRelayType == 1; + autoRelayFlag = autoRelayType == 1; if (lowVoltage.config.nominalBatteryVoltage == 0.0) { @@ -56,10 +56,10 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) // for these engine types secondary controller positions index MotorParam table if ((EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) && - ScndCtrlPosNo > MotorParametersArraySize) + scndCtrlPosNo > MotorParametersArraySize) { - WriteLog("SCPN=" + std::to_string(ScndCtrlPosNo) + " exceeds motor parameter table size, limited to " + std::to_string(MotorParametersArraySize)); - ScndCtrlPosNo = MotorParametersArraySize; + WriteLog("SCPN=" + std::to_string(scndCtrlPosNo) + " exceeds motor parameter table size, limited to " + std::to_string(MotorParametersArraySize)); + scndCtrlPosNo = MotorParametersArraySize; } // WriteLog("aa = " + AxleArangement + " " + std::string( Pos("o", AxleArangement)) ); @@ -67,7 +67,7 @@ bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) if (contains(AxleArangement, "o") && EngineType == TEngineType::ElectricSeriesMotor) { // test poprawnosci ilosci osi indywidualnie napedzanych - OK = RList[1].Bn * RList[1].Mn == NPoweredAxles; + OK = RList[1].Bn * RList[1].Mn == nPoweredAxles; // WriteLogSS("aa ok", BoolToYN(OK)); } @@ -226,7 +226,7 @@ void physics::Vehicle::CreateBrakeValve() case TBrakeValve::K: { WriteLog("XBT W, K"); - brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); if (brakes.config.maxPressureMass < 2) // jesli przystawka wazaca brakes.distributor->SetLP(0, brakes.config.maxCylinderPressure[3], 0); else @@ -236,7 +236,7 @@ void physics::Vehicle::CreateBrakeValve() case TBrakeValve::KE: { WriteLog("XBT WKE"); - brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); brakes.distributor->SetRM(brakes.config.rapidRatio); if (brakes.config.maxPressureMass < 2) // jesli przystawka wazaca brakes.distributor->SetLP(0, brakes.config.maxCylinderPressure[3], 0); @@ -250,7 +250,7 @@ void physics::Vehicle::CreateBrakeValve() case TBrakeValve::ESt4: { WriteLog("XBT NESt3, ESt3, ESt3AL2, ESt4"); - brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); static_cast(brakes.distributor.get())->SetSize(brakes.config.distributorSize, brakes.config.distributorParameters); if (brakes.config.maxPressureMass < 2) // jesli przystawka wazaca brakes.distributor->SetLP(0, brakes.config.maxCylinderPressure[3], 0); @@ -261,14 +261,14 @@ void physics::Vehicle::CreateBrakeValve() case TBrakeValve::LSt: { WriteLog("XBT LSt"); - brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); brakes.distributor->SetRM(brakes.config.rapidRatio); break; } case TBrakeValve::EStED: { WriteLog("XBT EStED"); - brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); brakes.distributor->SetRM(brakes.config.rapidRatio); if (brakes.config.maxPressureMass < 2) { @@ -284,14 +284,14 @@ void physics::Vehicle::CreateBrakeValve() case TBrakeValve::EP2: { WriteLog("XBT EP2"); - brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); brakes.distributor->SetLP(Mass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); break; } case TBrakeValve::EP1: { WriteLog("XBT EP1"); - brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); brakes.distributor->SetLP(Mass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); brakes.distributor->SetRM(brakes.config.rapidRatio); break; @@ -299,17 +299,17 @@ void physics::Vehicle::CreateBrakeValve() case TBrakeValve::CV1: { WriteLog("XBT CV1"); - brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); break; } case TBrakeValve::CV1_L_TR: { WriteLog("XBT CV1_L_T"); - brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); break; } default: - brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, NAxles, brakes.config.blocksPerAxle); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); } brakes.distributor->SetASBP(brakes.config.maxCylinderPressure[4]); @@ -364,7 +364,7 @@ void physics::Vehicle::CreateBrakeHandles() { brakes.independentValve = std::make_shared(); brakes.independentValve->Init(brakes.config.maxCylinderPressure[0]); - if (TrainType == train_type::emu) + if (trainType == train_type::emu) { dynamic_cast(brakes.independentValve.get())->SetSpeed(3.5); diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index 6767bac9c..03a61a753 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -76,14 +76,14 @@ double physics::Vehicle::Current(double n, double U) ResistorsFlag = RList[MainCtrlActualPos].R > 0.01; // and (!DelayCtrlFlag) ResistorsFlag = ResistorsFlag || (brakes.electrodynamic.on == true && brakes.electrodynamic.type == dbrake_automatic); - if (TrainType == train_type::et22 && DelayCtrlFlag && MainCtrlActualPos > 1) + if (trainType == train_type::et22 && delayCtrlFlag && MainCtrlActualPos > 1) Bn = 1.0 - 1.0 / RList[MainCtrlActualPos].Bn; else Bn = 1; // to jest wykonywane dla EU07 R = RList[MainCtrlActualPos].R * Bn + CircuitRes; - if (TrainType != train_type::emu || Imin != IminLo || false == ScndS) + if (trainType != train_type::emu || imin != IminLo || false == ScndS) { // yBARC - boczniki na szeregu poprawnie Mn = RList[MainCtrlActualPos].Mn; // to jest wykonywane dla EU07 @@ -133,7 +133,7 @@ double physics::Vehicle::Current(double n, double U) void physics::Vehicle::UpdateSeriesMotorDynamicBrakeFlag() { // i dzialanie hamulca ED w EP09 - if (brakes.electrodynamic.type == dbrake_automatic && TrainType != train_type::emu) + if (brakes.electrodynamic.type == dbrake_automatic && trainType != train_type::emu) { if ((brakes.distributor->GetEDBCP() < 0.25 && Vadd < 1) || brakes.cylinderPressure > 2.1) brakes.electrodynamic.on = false; @@ -141,7 +141,7 @@ void physics::Vehicle::UpdateSeriesMotorDynamicBrakeFlag() brakes.electrodynamic.on = true; brakes.electrodynamic.on = brakes.electrodynamic.on && lowVoltage.Is110vAvailable(); } - if (brakes.electrodynamic.type == dbrake_automatic && TrainType == train_type::emu) + if (brakes.electrodynamic.type == dbrake_automatic && trainType == train_type::emu) { brakes.electrodynamic.on = lowVoltage.Is110vAvailable() && (TUHEX_Active || Vadd > TUHEX_MinIw) && brakes.electrodynamic.emuWorking; } @@ -178,7 +178,7 @@ double physics::Vehicle::SeriesMotorCurrent(double const n, double const U, doub SP = RList[MainCtrlActualPos].ScndAct; } - Rz = Mn * WindingRes + R; + Rz = Mn * windingRes + R; if (brakes.electrodynamic.on) // hamowanie { @@ -191,9 +191,9 @@ double physics::Vehicle::SeriesMotorCurrent(double const n, double const U, doub 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 (brakes.electrodynamic.type == dbrake_switch && TrainType == train_type::et42) + if (brakes.electrodynamic.type == dbrake_switch && trainType == train_type::et42) { // z Megapacka - Rz = WindingRes + R; + Rz = windingRes + R; MotorCurrent = -motor_param(SP).fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} } } @@ -250,7 +250,7 @@ void physics::Vehicle::MotorFailuresCheck(double const n) { if (FuzzyLogic(abs(n), nmax * 1.1, p_elengproblem) && MainSwitch(false)) eventFlag = true; /*zbyt duze obroty - wywalanie wskutek ognia okreznego*/ - if (DamageFlag.HasAll(VehicleDamage::engine) && FuzzyLogic(MotorCurrent, (double)ImaxLo / 10.0, p_elengproblem) && MainSwitch(false)) + if (DamageFlag.HasAll(VehicleDamage::engine) && FuzzyLogic(MotorCurrent, (double)imaxLo / 10.0, p_elengproblem) && MainSwitch(false)) eventFlag = true; /*uszkodzony silnik (uplywy)*/ /* or FuzzyLogic(Abs(U/Mn),2*NominalVoltage,1)) then */ /*poprawic potem*/ if ((FuzzyLogic(abs(Im), Imax * 2, p_elengproblem) || FuzzyLogic(abs(n), nmax * 1.11, p_elengproblem)) && DamageFlag.Set(VehicleDamage::engine)) @@ -278,7 +278,7 @@ bool physics::Vehicle::CurrentSwitch(bool const State) if (MaxCurrentSwitch(State)) { - if (TrainType != train_type::emu) + if (trainType != train_type::emu) { MinCurrentSwitch(State); } @@ -291,7 +291,7 @@ bool physics::Vehicle::CurrentSwitch(bool const State) bool physics::Vehicle::IsMotorOverloadRelayHighThresholdOn() const { - return ImaxHi > ImaxLo && Imax > ImaxLo; + return imaxHi > imaxLo && Imax > imaxLo; } double physics::Vehicle::ShowEngineRotation(int VehN) const @@ -568,18 +568,18 @@ bool physics::Vehicle::DynamicBrakeSwitch(bool Switch) // ************************************************************************************************* double physics::Vehicle::TractionForce(double dt) { - Ft = 0; + ft = 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); + eAngleValue += enrot * dt; + if (eAngleValue > M_PI * 2.0) + eAngleValue = std::fmod(eAngleValue, M_PI * 2.0); /* - while (eAngle > M_PI * 2.0) + while (eAngleValue > M_PI * 2.0) // eAngle = Pirazy2 - eAngle; <- ABu: a nie czasem tak, jak nizej? - eAngle -= M_PI * 2.0; + eAngleValue -= M_PI * 2.0; */ // hunter-091012: przeniesione z if DirActive<>0 (zeby po zejsciu z kierunku dalej spadala predkosc wentylatorow) // wentylatory rozruchowe @@ -596,7 +596,7 @@ double physics::Vehicle::TractionForce(double dt) } drive.AfterTractionForce(*this); - return Ft; + return ft; } // the starting resistors' blowers, and the diesels' radiator fans @@ -626,15 +626,15 @@ void physics::Vehicle::UpdateResistorBlowers(double dt) case 2: { // automatic - auto const motorcurrent{std::min(ImaxHi, std::abs(Im))}; + 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; + RventRot += (RVentnmax * std::min(1.0, motorcurrent / nPoweredAxles / RVentMinI) * motorcurrent / imaxLo - RventRot) * RVentSpeed * dt; } else if (brakes.electrodynamic.type == dbrake_automatic && true == brakes.electrodynamic.on) { - RventRot += (RVentnmax * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; + RventRot += (RVentnmax * motorcurrent / imaxLo - RventRot) * RVentSpeed * dt; } else if (rventForceOn) { @@ -672,24 +672,24 @@ void physics::Vehicle::DumbTractionForce(double const PosRatio) { if (Vel > 0.1) { - Ft = std::min(1000.0 * Power / std::abs(travelSpeed), Ftmax) * PosRatio; + ft = std::min(1000.0 * Power / std::abs(travelSpeed), Ftmax) * PosRatio; } else { - Ft = Ftmax * PosRatio; + ft = Ftmax * PosRatio; } - Ft = Ft * DirAbsolute; // DirActive*CabActive; + ft = ft * DirAbsolute; // DirActive*CabActive; } else { - Ft = 0; + ft = 0; } } void physics::Vehicle::WheelsDrivenTractionForce(double dt) { if (EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) - Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; + ft = Sign(sin(eAngleValue)) * PulseForce * Transmision.Ratio; PulseForceTimer = PulseForceTimer + dt; if (PulseForceTimer > CtrlDelay) { @@ -697,20 +697,20 @@ void physics::Vehicle::WheelsDrivenTractionForce(double dt) if (PulseForceCount > 0) PulseForceCount--; } - EnginePower = Ft * (1.0 + Vel); + EnginePower = ft * (1.0 + Vel); } void physics::Vehicle::SeriesMotorTractionForce(double dt) { // enrot:=Transmision.Ratio*nrot; // yB: szereg dwoch sekcji w ET42 - if (TrainType == train_type::et42 && Imax == ImaxHi) + if (trainType == train_type::et42 && Imax == imaxHi) EngineVoltage = EngineVoltage / 2.0; Mm = Momentum(Current(enrot, EngineVoltage)); // oblicza tez prad p/slinik - if (TrainType == train_type::et42) + if (trainType == train_type::et42) { - if (Imax == ImaxHi) + if (Imax == imaxHi) EngineVoltage = EngineVoltage * 2; if (brakes.electrodynamic.on && abs(Im) > 300) // przeiesione do physics.cpp FuseOff(); @@ -720,7 +720,7 @@ void physics::Vehicle::SeriesMotorTractionForce(double dt) SeriesMotorDynamicBrake(dt); } - if (TrainType == train_type::et22 && DelayCtrlFlag) // szarpanie przy zmianie układu w byku + if (trainType == train_type::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) @@ -732,13 +732,13 @@ void physics::Vehicle::SeriesMotorTractionForce(double dt) if ((brakes.electrodynamic.type == dbrake_automatic || brakes.electrodynamic.type == dbrake_switch) && brakes.electrodynamic.on) Itot = Im * 2; // 2x2 silniki w EP09 - else if (TrainType == train_type::emu && Imin == IminLo && ScndS) // yBARC - boczniki na szeregu poprawnie + else if (trainType == train_type::emu && 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 + 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) @@ -804,7 +804,7 @@ void physics::Vehicle::ShuntFieldRelaysCheck(double const tmpV, double const Pos case 0: { - if (scndCtrlPos < ScndCtrlPosNo && Im <= MPTRelay[scndCtrlPos].Iup * PosRatio) + if (scndCtrlPos < scndCtrlPosNo && Im <= MPTRelay[scndCtrlPos].Iup * PosRatio) { ++scndCtrlPos; } @@ -817,7 +817,7 @@ void physics::Vehicle::ShuntFieldRelaysCheck(double const tmpV, double const Pos case 1: { - if (scndCtrlPos < ScndCtrlPosNo && MPTRelay[scndCtrlPos].Iup < Vel) + if (scndCtrlPos < scndCtrlPosNo && MPTRelay[scndCtrlPos].Iup < Vel) { ++scndCtrlPos; } @@ -863,7 +863,7 @@ void physics::Vehicle::ShuntFieldRelaysCheck(double const tmpV, double const Pos // 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 physics::Vehicle::ShuntFieldRelaysType2(double const tmp) { - if (scndCtrlPos < ScndCtrlPosNo && MPTRelay[scndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) + if (scndCtrlPos < scndCtrlPosNo && MPTRelay[scndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) { ++scndCtrlPos; } @@ -876,7 +876,7 @@ void physics::Vehicle::ShuntFieldRelaysType2(double const tmp) // the relays of type 41: up by the speed tmpV at full power, the engine slowed down, down by the current void physics::Vehicle::ShuntFieldRelaysType41(double const tmpV) { - if (scndCtrlPos < ScndCtrlPosNo && mainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[scndCtrlPos].Iup) + if (scndCtrlPos < scndCtrlPosNo && mainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[scndCtrlPos].Iup) { ++scndCtrlPos; enrot = enrot * 0.73; @@ -890,7 +890,7 @@ void physics::Vehicle::ShuntFieldRelaysType41(double const tmpV) // 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 physics::Vehicle::ShuntFieldRelaysType45() { - if (scndCtrlPos < ScndCtrlPosNo && mainCtrlPos >= 11) + if (scndCtrlPos < scndCtrlPosNo && mainCtrlPos >= 11) { if (Im < MPTRelay[scndCtrlPos].Iup) @@ -946,7 +946,7 @@ void physics::Vehicle::ShuntFieldRelaysType45() void physics::Vehicle::ShuntFieldRelaysType46() { // wzrastanie - if (mainCtrlPos >= 12 && scndCtrlPos < ScndCtrlPosNo) + if (mainCtrlPos >= 12 && scndCtrlPos < scndCtrlPosNo) { ShuntFieldRelaysType46Up(); } @@ -1025,7 +1025,7 @@ void physics::Vehicle::InductionMotorTractionForce(double 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) + if (slippingWheels) { PosRatio = 0; tmp = 10; @@ -1056,11 +1056,11 @@ void physics::Vehicle::InductionMotorTractionForce(double dt) void physics::Vehicle::InductionMotorSpeedControl(double dt) { // tempomat - if (ScndCtrlPosNo == 4 && SpeedCtrlTypeTime) + if (scndCtrlPosNo == 4 && speedCtrlTypeTime) { SpeedControlByTime(dt); } - else if (ScndCtrlPosNo > 1) + else if (scndCtrlPosNo > 1) { SpeedControlByPosition(dt); } @@ -1069,18 +1069,18 @@ void physics::Vehicle::InductionMotorSpeedControl(double dt) // the speed control set by the position of the second controller, after it's been held for its delay void physics::Vehicle::SpeedControlByPosition(double dt) { - if (scndCtrlPos != NewSpeed) + if (scndCtrlPos != newSpeed) { SpeedCtrlTimer = 0; - NewSpeed = scndCtrlPos; + newSpeed = scndCtrlPos; } else { SpeedCtrlTimer += dt; if (SpeedCtrlTimer > SpeedCtrlDelay) { - auto NewSCAP = static_cast((float)scndCtrlPos / (float)ScndCtrlPosNo * Vmax); + auto NewSCAP = static_cast((float)scndCtrlPos / (float)scndCtrlPosNo * vmax); if (NewSCAP != SpeedCtrlValue) { SpeedCtrlValue = NewSCAP; @@ -1099,7 +1099,7 @@ void physics::Vehicle::SpeedControlByTime(double dt) switch (scndCtrlPos) { case 0: - NewSpeed = 0; + newSpeed = 0; SpeedCtrlValue = 0; SpeedCtrlTimer = 10; break; @@ -1107,31 +1107,31 @@ void physics::Vehicle::SpeedControlByTime(double dt) if (SpeedCtrlTimer > SpeedCtrlDelay) { SpeedCtrlTimer = 0; - NewSpeed -= 10; - if (NewSpeed < 0) - NewSpeed = 0; + newSpeed -= 10; + if (newSpeed < 0) + newSpeed = 0; } else SpeedCtrlTimer += dt; break; case 2: SpeedCtrlTimer = 10; - SpeedCtrlValue = NewSpeed; + SpeedCtrlValue = newSpeed; break; case 3: if (SpeedCtrlTimer > SpeedCtrlDelay) { SpeedCtrlTimer = 0; - NewSpeed += 10; - if (NewSpeed > Vmax) - NewSpeed = Vmax; + newSpeed += 10; + if (newSpeed > vmax) + newSpeed = vmax; } else SpeedCtrlTimer += dt; break; case 4: - NewSpeed = Vmax; - SpeedCtrlValue = Vmax; + newSpeed = vmax; + SpeedCtrlValue = vmax; SpeedCtrlTimer = 10; break; default: @@ -1157,7 +1157,7 @@ void physics::Vehicle::InductionMotorBrakeBlending(double const ActiveInverters, if (Flat && inductionMotor.traction.startingForce * inductionMotor.state.fullForce > 0) PosRatio = std::min(PosRatio * inductionMotor.traction.startingForce / inductionMotor.state.fullForce, 1.); /* if (ScndCtrlActualPos > 0) //speed control - if (Vmax < 250) + if (vmax < 250) PosRatio = std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos - Vel))); else PosRatio = @@ -1265,7 +1265,7 @@ void physics::Vehicle::InductionMotorDrive(double dt) } inductionMotor.state.absoluteMaxForce = 0.001 * square(std::min(1.0, inductionMotor.state.criticalFrequency / std::max(abs(enrot) * inductionMotor.motor.polePairs + inductionMotor.motor.maxSlipFrequency * inductionMotor.state.slipShare, inductionMotor.motor.maxSlipFrequency)) * f_cfu / inductionMotor.motor.voltsPerHertz) * - (inductionMotor.motor.maxSlipFrequency * inductionMotor.motor.currentPerSlip * inductionMotor.motor.torquePerCurrent) * Transmision.Ratio * NPoweredAxles * 2.0 / WheelDiameter; + (inductionMotor.motor.maxSlipFrequency * inductionMotor.motor.currentPerSlip * inductionMotor.motor.torquePerCurrent) * Transmision.Ratio * nPoweredAxles * 2.0 / wheelDiameter; InductionMotorForceLimits(); for (auto &inv : inductionMotor.inverters) { @@ -1286,8 +1286,8 @@ void physics::Vehicle::InductionMotorDrive(double dt) inductionMotor.state.torqueCurrent = (inductionMotor.state.supplyFrequency - DirAbsolute * enrot * inductionMotor.motor.polePairs) * inductionMotor.motor.currentPerSlip * inductionMotor.state.flux; inductionMotor.state.fieldCurrent = inductionMotor.state.torqueCurrent * inductionMotor.motor.fieldCurrentRatio; inductionMotor.state.torque = inductionMotor.state.flux * inductionMotor.state.torqueCurrent * inductionMotor.motor.torquePerCurrent; - inductionMotor.state.lineCurrent = inductionMotor.state.torqueCurrent * NPoweredAxles * inductionMotor.inverterRatio * inductionMotor.state.voltage / (EngineVoltage - inductionMotor.converter.voltageDrop) + inductionMotor.converter.noLoadCurrent; - inductionMotor.state.mechanicalPower = DirActive * inductionMotor.state.torque * NPoweredAxles * inductionMotor.inverterRatio * enrot * Pirazy2 / 1000; + inductionMotor.state.lineCurrent = inductionMotor.state.torqueCurrent * nPoweredAxles * inductionMotor.inverterRatio * inductionMotor.state.voltage / (EngineVoltage - inductionMotor.converter.voltageDrop) + inductionMotor.converter.noLoadCurrent; + inductionMotor.state.mechanicalPower = DirActive * inductionMotor.state.torque * nPoweredAxles * inductionMotor.inverterRatio * enrot * Pirazy2 / 1000; inductionMotor.state.electricalPower = inductionMotor.state.lineCurrent * EngineVoltage / 1000; inductionMotor.state.efficiency = inductionMotor.state.mechanicalPower / inductionMotor.state.electricalPower; @@ -1302,15 +1302,15 @@ void physics::Vehicle::InductionMotorDrive(double dt) Vadd = std::max(Vadd * (1.0 - 0.2 * dt), 0.007 * (std::abs(EngineVoltage) - (EnginePowerSource.CollectorParameters.MaxV - 100))); Itot = inductionMotor.state.lineCurrent * (0.01 + std::min(0.99, 0.99 - Vadd)); - EnginePower = abs(inductionMotor.state.torqueCurrent * inductionMotor.state.voltage * NPoweredAxles) / 1000; + EnginePower = abs(inductionMotor.state.torqueCurrent * inductionMotor.state.voltage * nPoweredAxles) / 1000; // power inverters UpdateInverterFrequency(); Mm = inductionMotor.state.torque * DirAbsolute; Mw = Mm * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter; - Ft = Fw * NPoweredAxles * inductionMotor.inverterRatio; - inductionMotor.state.force = DirAbsolute * Ft / 1000; + Fw = Mw * 2.0 / wheelDiameter; + ft = Fw * nPoweredAxles * inductionMotor.inverterRatio; + inductionMotor.state.force = DirAbsolute * ft / 1000; } // the force the motors give at full and at the setting (inductionMotor.forceShare), braking within the power and the force of the @@ -1378,7 +1378,7 @@ void physics::Vehicle::InductionMotorOff() Mm = 0.0; Mw = 0.0; Fw = 0.0; - Ft = 0.0; + ft = 0.0; Itot = 0.0; inductionMotor.forceShare = 0.0; EnginePower = 0.0; @@ -1512,18 +1512,18 @@ double physics::Vehicle::v2n(void) double n; double deltan = 0; - n = travelSpeed / (M_PI * WheelDiameter); // predkosc obrotowa wynikajaca z liniowej [obr/s] - deltan = n - nrot; //"pochodna" prędkości obrotowej - /* if (SlippingWheels) + n = travelSpeed / (M_PI * wheelDiameter); // predkosc obrotowa wynikajaca z liniowej [obr/s] + deltan = n - nrotValue; //"pochodna" prędkości obrotowej + /* if (slippingWheels) if (std::abs(deltan) < 0.001) - SlippingWheels = false; // wygaszenie poslizgu */ //poslizg jest w innym miejscu wygaszany też - if (SlippingWheels) // nie ma zwiazku z predkoscia liniowa V + slippingWheels = false; // wygaszenie poslizgu */ //poslizg jest w innym miejscu wygaszany też + if (slippingWheels) // nie ma zwiazku z predkoscia liniowa V { // McZapkie-221103: uszkodzenia kol podczas poslizgu if (deltan > dmgn && FuzzyLogic(deltan, dmgn, p_slippdmg) && DamageFlag.Set(VehicleDamage::wheelWear)) // podkucie eventFlag = true; if (deltan < -dmgn && FuzzyLogic(-deltan, dmgn, p_slippdmg) && DamageFlag.Set(VehicleDamage::thinWheel)) // wycieranie sie obreczy eventFlag = true; - n = nrot; // predkosc obrotowa nie zalezy od predkosci liniowej + n = nrotValue; // predkosc obrotowa nie zalezy od predkosci liniowej } return n; } @@ -1563,9 +1563,9 @@ double physics::Vehicle::MomentumF(double I, double Iw, int SCP) const bool physics::Vehicle::CutOffEngine(void) { bool COE = false; // Ra: wartość domyślna, sprawdzić to trzeba - if (NPoweredAxles > 0 && CabActive == 0 && EngineType == TEngineType::ElectricSeriesMotor && DamageFlag.Clear(VehicleDamage::engine)) + if (nPoweredAxles > 0 && CabActive == 0 && EngineType == TEngineType::ElectricSeriesMotor && DamageFlag.Clear(VehicleDamage::engine)) { - NPoweredAxles = NPoweredAxles / 2; // bylo div czyli mod? + nPoweredAxles = nPoweredAxles / 2; // bylo div czyli mod? COE = true; } return COE; @@ -1577,9 +1577,9 @@ bool physics::Vehicle::CutOffEngine(void) // ************************************************************************************************* bool physics::Vehicle::MaxCurrentSwitch(bool State, range_t const Notify) { - auto const initialstate{MotorOverloadRelayHighThreshold}; + auto const initialstate{motorOverloadRelayHighThreshold}; - MotorOverloadRelayHighThreshold = State; + motorOverloadRelayHighThreshold = State; if (Notify != range_t::local) { @@ -1596,19 +1596,19 @@ bool physics::Vehicle::MaxCurrentSwitch(bool State, range_t const Notify) bool physics::Vehicle::MinCurrentSwitch(bool State) { bool MCS = false; - if ((EngineType == TEngineType::ElectricSeriesMotor && IminHi > IminLo) || (TrainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor)) + if ((EngineType == TEngineType::ElectricSeriesMotor && IminHi > IminLo) || (trainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor)) { - if (State && Imin == IminLo) + if (State && imin == IminLo) { - Imin = IminHi; + imin = IminHi; MCS = true; if (CabActive != 0) SendCtrlToNext(VehicleCommand::minCurrentSwitch, 1, CabActive); } - if (!State && Imin == IminHi) + if (!State && imin == IminHi) { - Imin = IminLo; + imin = IminLo; MCS = true; if (CabActive != 0) SendCtrlToNext(VehicleCommand::minCurrentSwitch, 0, CabActive); @@ -1646,7 +1646,7 @@ double physics::Vehicle::ShowCurrentP(int AmpN) const bool Grupowy; // ClearPendingExceptions; - Grupowy = DelayCtrlFlag && TrainType == train_type::et22; // przerzucanie walu grupowego w ET22; + Grupowy = delayCtrlFlag && trainType == train_type::et22; // przerzucanie walu grupowego w ET22; Bn = RList[MainCtrlActualPos].Bn; // ile równoległych gałęzi silników if (brakes.electrodynamic.type == dbrake_automatic && brakes.electrodynamic.on) diff --git a/physics/consistbraking.cpp b/physics/consistbraking.cpp index 423b636e4..455fdaa28 100644 --- a/physics/consistbraking.cpp +++ b/physics/consistbraking.cpp @@ -70,7 +70,7 @@ void physics::ConsistBrakeBlending::SetControl(Step &state, Vehicle &Lead, Input Lead.CheckEIMIC(dt1); Lead.CheckSpeedCtrl(dt1); - state.eimic = std::min(Lead.eimic, Lead.eimicSpeedCtrl); + state.eimic = std::min(Lead.eimic, Lead.eimicSpeedCtrl()); Lead.eimic_real = state.eimic; // Elf: full braking at once in the lowest position, and in the emergency brake position below it if (Lead.EIMCtrlType == 2 && Lead.MainCtrlPos() <= Lead.EIMCtrlEmergencyPositions()) @@ -101,18 +101,18 @@ void physics::ConsistBrakeBlending::SumForces(Step &state, std::vectorbrakes.config.maxPressureMass > 1.0 ? 0.0 : vehicle->Mass ) - + vehicle->Mred; + + vehicle->Mred(); auto const Nmax = ((vehicle->brakes.config.pressureToForce * vehicle->brakes.config.maxCylinderPressure[0] - vehicle->brakes.config.cylinders.springForce) * vehicle->brakes.config.cylinders.leverRatio[0] - vehicle->brakes.config.cylinders.slackAdjusterForce) * vehicle->brakes.config.cylinders.count * vehicle->brakes.config.cylinders.riggingEfficiency; state.FmaxPN += Nmax * vehicle->brakes.distributor->GetFC( - Nmax / (vehicle->NAxles * vehicle->brakes.config.blocksPerAxle), + Nmax / (vehicle->NAxles() * vehicle->brakes.config.blocksPerAxle), vehicle->brakes.blending.referenceSpeed) * 1000; // sila hamowania pn state.FmaxED += vehicle->lineBreaker.IsClosed() && vehicle->DirActive != 0 && vehicle->inductionMotor.inverterRatio == 1.0 && - vehicle->inductionMotor.braking.maxForce * vehicle->NPoweredAxles > 0 ? + vehicle->inductionMotor.braking.maxForce * vehicle->NPoweredAxles() > 0 ? vehicle->inductionMotor.braking.maxForce * 1000 : 0; // chwilowy max ED -> do rozdzialu sil FED -= std::min(vehicle->inductionMotor.state.maxForce, 0.0) * @@ -123,8 +123,8 @@ void physics::ConsistBrakeBlending::SumForces(Step &state, std::vector do pneumatyki Frj += std::max(vehicle->inductionMotor.state.maxForce, 0.0) * 1000;// chwilowo realizowany napęd -> do utrzymującego - state.masa += vehicle->TotalMass; - state.osie += vehicle->NAxles; + state.masa += vehicle->TotalMass(); + state.osie += vehicle->NAxles(); } } @@ -217,7 +217,7 @@ void physics::ConsistBrakeBlending::ComputeElectrodynamicDemand(Step &state, Veh if( state.LBR > Lead.brakes.blending.minEdDemand && ( Lead.brakes.config.driverValveType == TBrakeHandle::MHZ_EN57 ? (Lead.brakes.operatingMode & bom_MED) != 0 : - Lead.EpFuse ) ) { + Lead.EpFuse() ) ) { state.FzadED = std::min( state.Fzad, state.FmaxED ); } /*/ELF - wdrazanie ED po powrocie na utrzymanie hamowania - do usuniecia @@ -280,14 +280,14 @@ void physics::ConsistBrakeBlending::DistributeForces(Step &state, Vehicle const vehicle->brakes.config.cylinders.count * vehicle->brakes.config.cylinders.riggingEfficiency; FmaxEP[i] = Nmax * vehicle->brakes.distributor->GetFC( - Nmax / (vehicle->NAxles * vehicle->brakes.config.blocksPerAxle), + Nmax / (vehicle->NAxles() * vehicle->brakes.config.blocksPerAxle), vehicle->brakes.blending.referenceSpeed) * 1000; // sila hamowania pn PrzekrF[i] = false; FzED[i] = state.FmaxED > 0 ? state.FzadED / state.FmaxED : 0; vehicle->SetAnPos(Lead.ScndS ? state.LBR : FzED[i]); - FzEP[ i ] = static_cast( state.FzadPN * vehicle->NAxles ) / static_cast( state.osie ); + FzEP[ i ] = static_cast( state.FzadPN * vehicle->NAxles() ) / static_cast( state.osie ); ++i; vehicle->ShuntMode = Lead.ShuntMode; vehicle->ShuntModeAllow = Lead.ShuntModeAllow; @@ -300,12 +300,12 @@ void physics::ConsistBrakeBlending::DistributeForces(Step &state, Vehicle const for (auto *vehicle : Consist) { if (FzEP[i] > 0.01 && - FzEP[i] > vehicle->TotalMass * vehicle->inductionMotor.braking.maxEpDeceleration + std::min(vehicle->inductionMotor.state.maxForce, 0.) * 1000 && + FzEP[i] > vehicle->TotalMass() * vehicle->inductionMotor.braking.maxEpDeceleration + std::min(vehicle->inductionMotor.state.maxForce, 0.) * 1000 && !PrzekrF[i]) { float przek1 = -std::min(vehicle->inductionMotor.state.maxForce, 0.) * 1000 + FzEP[i] - - vehicle->TotalMass * + vehicle->TotalMass() * vehicle->inductionMotor.braking.maxEpDeceleration * 0.999; PrzekrF[i] = true; test = true; @@ -345,7 +345,7 @@ void physics::ConsistBrakeBlending::DistributeForces(Step &state, Vehicle const float VelC = EPVC ? safe_clamp(vehicle->Vel, vehicle->brakes.blending.minSpeed, vehicle->brakes.blending.maxSpeed) : vehicle->brakes.blending.referenceSpeed;//korekcja EP po prędkości float FmaxPoj = Nmax * vehicle->brakes.distributor->GetFC( - Nmax / (vehicle->NAxles * vehicle->brakes.config.blocksPerAxle), VelC) * + Nmax / (vehicle->NAxles() * vehicle->brakes.config.blocksPerAxle), VelC) * 1000; // sila hamowania pn vehicle->brakes.SetIndependentPositionEim(FzEP[i] / FmaxPoj); if (vehicle->brakes.IndependentPositionEim()>0.009) diff --git a/physics/vehicle.h b/physics/vehicle.h index 4d6cc4277..3e6a68ab6 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -449,7 +449,7 @@ class TSecuritySystem bool is_engine_blocked() const; bool radiostop_available() const; bool has_separate_acknowledge() const; - void load(std::string const &line, double Vmax); + void load(std::string const &line, double vmax); double MagnetLocation = 0.0; }; @@ -629,11 +629,11 @@ class Vehicle int CategoryFlag = 1; /*1 - pociag, 2 - samochod, 4 - statek, 8 - samolot*/ /*--sekcja stalych typowych parametrow*/ std::string TypeName; /*nazwa serii/typu*/ - train_type TrainType{train_type::generic}; // the vehicles of a handling of their own, from the Type of the .fiz + train_type const &TrainType() const { return trainType; } // the vehicles of a handling of their own, from the Type of the .fiz // an electric or a diesel multiple unit bool is_multiple_unit() const { - return TrainType == train_type::emu || TrainType == train_type::dmu; + return trainType == train_type::emu || trainType == train_type::dmu; } TEngineType EngineType = TEngineType::None; /*typ napedu*/ TPowerParameters EnginePowerSource; /*zrodlo mocy dla silnikow*/ @@ -642,13 +642,13 @@ class Vehicle TPowerParameters AlterHeatPowerSource; /*alternatywne zrodlo mocy dla ogrzewania*/ TPowerParameters LightPowerSource; /*zrodlo mocy dla oswietlenia*/ TPowerParameters AlterLightPowerSource; /*alternatywne mocy dla oswietlenia*/ - double Vmax = -1.0; + double const &Vmax() const { return vmax; } double Mass = 0.0; double Power = 0.0; /*max. predkosc kontrukcyjna, masa wlasna, moc*/ - double Mred = 0.0; /*Ra: zredukowane masy wirujące; potrzebne do obliczeń hamowania*/ - double TotalMass = 0.0; /*wyliczane przez ComputeMass*/ + double const &Mred() const { return mred; } /*Ra: zredukowane masy wirujące; potrzebne do obliczeń hamowania*/ + double const &TotalMass() const { return totalMass; } /*wyliczane przez ComputeMass*/ double LightPower = 0.0; /*moc pobierana na ogrzewanie/oswietlenie*/ - bool EpFuse = true; /*Czy jest wlaczony hamulec EP*/ + bool const &EpFuse() const { return epFuse; } /*Czy jest wlaczony hamulec EP*/ double EpForce = 0.0; /*Poziom zadanej sily EP*/ bool const &Signalling() const { return signalling; } /*Czy jest zalaczona sygnalizacja hamowania ostatniego wagonu*/ void SetSignalling(bool const Value) { signalling = Value; } @@ -664,17 +664,17 @@ class Vehicle // 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 const &WheelDiameter() const { return wheelDiameter; } /*srednica kol napednych*/ float WheelDiameterL = 0.9f; // Ra: srednica kol tocznych przednich float WheelDiameterT = 0.9f; // Ra: srednica kol tocznych tylnych float TrackW = 1.435f; /*nominalna szerokosc toru [m]*/ double AxleInertialMoment = 0.0; /*moment bezwladnosci zestawu kolowego*/ std::string AxleArangement; /*uklad osi np. Bo'Bo' albo 1'C*/ - int NPoweredAxles = 0; /*ilosc osi napednych liczona z powyzszego*/ - int NAxles = 0; /*ilosc wszystkich osi j.w.*/ + int const &NPoweredAxles() const { return nPoweredAxles; } /*ilosc osi napednych liczona z powyzszego*/ + int const &NAxles() const { return nAxles; } /*ilosc wszystkich osi j.w.*/ int BearingType = 1; /*lozyska: 0 - slizgowe, 1 - toczne*/ - double ADist = 0.0; - double BDist = 0.0; /*odlegosc osi oraz czopow skretu*/ + double const &ADist() const { return aDist; } + double const &BDist() const { return bDist; } /*odlegosc osi oraz czopow skretu*/ int SandCapacity = 0; /*zasobnik piasku [kg]*/ int const &WiperSwitchPos() const { return wiperSwitchPos; } // pozycja przelacznika wycieraczek @@ -699,7 +699,7 @@ class Vehicle int TurboTest = 0; /*nastawniki:*/ int MainCtrlPosNo = 0; /*ilosc pozycji nastawnika*/ - int ScndCtrlPosNo = 0; + int const &ScndCtrlPosNo() const { return scndCtrlPosNo; } int LightsPosNo = 0; int LightsDefPos = 1; bool LightsWrap = false; @@ -719,7 +719,7 @@ class Vehicle float DistanceCounterDoublePressPeriod = {1.f}; // czas w jakim nalezy podwojnie wcisnac przycisk, aby rozpoczac pomiar odleglosci TSecuritySystem SecuritySystem; int EmergencyBrakeWarningSignal{0}; // combined with basic warningSignal when manual emergency brake is active - horn_supply HornSupply{horn_supply::air}; // of the low and high tone horns (warningSignal 1 and 2) + horn_supply const &HornSupply() const { return hornSupply; } // of the low and high tone horns (warningSignal 1 and 2) horn_supply Horn3Supply{horn_supply::air}; // of the third horn (warningSignal 4) // main reservoir pressure [bar, as MinCP and MaxCP] below which a pneumatic horn stays silent static constexpr double HornMinPressure{2.0}; @@ -727,12 +727,12 @@ class Vehicle int UniCtrlListSize = 0; /*wielkosc listy pozycji uniwersalnego nastawnika*/ bool UniCtrlIntegratedBrakePNCtrl = false; /*zintegrowany nastawnik JH obsluguje hamulec PN*/ bool UniCtrlIntegratedBrakeCtrl = false; /*zintegrowany nastawnik JH obsluguje hamowanie*/ - bool UniCtrlIntegratedLocalBrakeCtrl = false; /*zintegrowany nastawnik JH obsluguje hamowanie hamulcem pomocniczym*/ + bool const &UniCtrlIntegratedLocalBrakeCtrl() const { return uniCtrlIntegratedLocalBrakeCtrl; } /*zintegrowany nastawnik JH obsluguje hamowanie hamulcem pomocniczym*/ int UniCtrlNoPowerPos{0}; // cached highesr position not generating traction force // UCList CtrlValStep: the universal controller (EIMCtrlType 3) changes its setting in steps of this size (e.g. 0.05 for the // 5% steps of the 6Dg), one at once when moved to a raising or lowering position, then one each time its SpeedUp / SpeedDown // covers a step; 0 (the default) changes it continuously - double UniCtrlValStep{0.0}; + double const &UniCtrlValStep() const { return uniCtrlValStep; } /*-sekcja parametrow dla lokomotywy elektrycznej*/ TSchemeTable RList; /*lista rezystorow rozruchowych i polaczen silnikow, dla dizla: napelnienia*/ @@ -755,24 +755,24 @@ class Vehicle // Ratio: real; {NToothW/NToothM} // end; double NominalVoltage = 0.0; /*nominalne napiecie silnika*/ - double WindingRes = 0.0; + double const &WindingRes() const { return windingRes; } double u = 0.0; // wspolczynnik tarcia yB wywalic!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! double CircuitRes = 0.0; /*rezystancje silnika i obwodu*/ int IminLo = 0; int IminHi = 0; /*prady przelacznika automatycznego rozruchu, uzywane tez przez ai_driver*/ - int ImaxLo = 0; // maksymalny prad niskiego rozruchu - int ImaxHi = 0; // maksymalny prad wysokiego rozruchu - bool MotorOverloadRelayHighThreshold{false}; + int const &ImaxLo() const { return imaxLo; } // maksymalny prad niskiego rozruchu + int const &ImaxHi() const { return imaxHi; } // maksymalny prad wysokiego rozruchu + bool const &MotorOverloadRelayHighThreshold() const { return motorOverloadRelayHighThreshold; } double nmax = 0.0; /*maksymalna dop. ilosc obrotow /s*/ - double InitialCtrlDelay = 0.0; + double const &InitialCtrlDelay() const { return initialCtrlDelay; } double CtrlDelay = 0.0; /* -//- -//- miedzy kolejnymi poz.*/ double CtrlDownDelay = 0.0; /* -//- -//- przy schodzeniu z poz.*/ /*hunter-101012*/ 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*/ + int const &AutoRelayType() const { return autoRelayType; } /*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 const &FieldShuntSwitch() const { return fieldShuntSwitch; } bool CoupledCtrl = false; /*czy mainctrl i scndctrl sa sprzezone*/ bool HasCamshaft{false}; // the dynamic brake of a diesel-electric vehicle (Engine: EDBrake=...): the traction motors brake into resistors while @@ -891,7 +891,7 @@ class Vehicle void SetMirrorForbidden(bool const Value) { mirrorForbidden = Value; } bool ScndS = false; /*Czy jest bocznikowanie na szeregowej*/ bool ScndCtrlResistiveLock{false}; // the shunt controller can't be moved, up or down, while the master controller is at zero or on a resistive position, and drops to 0 when the master controller gets there (ScndCtrlResistiveLock=Yes in Cntrl.) - bool SpeedCtrl = false; /*czy jest tempomat*/ + bool const &SpeedCtrl() const { return speedCtrl; } /*czy jest tempomat*/ speed_control SpeedCtrlUnit; /*parametry tempomatu*/ double SpeedCtrlButtons[10]{30, 40, 50, 60, 70, 80, 90, 100, 110, 120}; /*przyciski prędkości*/ double SpeedCtrlDelay = 2; /*opoznienie dzialania tempomatu z wybieralna predkoscia*/ @@ -916,7 +916,9 @@ class Vehicle // the events of the step the sounds are to follow up (sound::), cleared once they did int SoundFlag() const { return soundFlag; } void ClearSoundFlags() { soundFlag = 0; } - int AIFlag{0}; // HACK: events of interest for consist owner + int const &AIFlag() const { return aiFlag; } // HACK: events of interest for consist owner + // the flag of an event the AI has seen to + void ClearAIFlag(int Flag); double const &DistCounter() const { return distCounter; } /*! licznik kilometrow */ void SetDistCounter(double const Value) { distCounter = Value; } // the criteria of derailment (physics.derailment new), and the distance travelled since they were checked [m] @@ -926,7 +928,7 @@ class Vehicle // 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; + int const &derailment_reports() const { return derailmentreportsValue; } odometer::reading Odometer; // total distance run, kept between the sessions (eu07/maszyna#72) std::pair EnergyMeter; // energy from grid [kWh] double const &V() const { return travelSpeed; } // predkosc w [m/s] względem sprzęgów (dodania gdy jedzie w stronę 0) @@ -934,7 +936,7 @@ class Vehicle double Vel = 0.0; // moduł prędkości w [km/h], używany przez AI double const &AccS() const { return accS; } // efektywne przyspieszenie styczne w [m/s^2] (wszystkie siły) void SetAccS(double const Value) { accS = Value; } - double AccSVBased{}; // tangential acceleration calculated from velocity change + double const &AccSVBased() const { return accSVBased; } // tangential acceleration calculated from velocity change double const &AccN() const { return accN; } // przyspieszenie normalne w [m/s^2] void SetAccN(double const Value) { accN = Value; } double const &AccVert() const { return accVert; } // vertical acceleration @@ -946,7 +948,7 @@ class Vehicle accS += Acceleration; accN += Acceleration; } - double nrot = 0.0; // predkosc obrotowa kol (obrotow na sekunde) + double const &nrot() const { return nrotValue; } // predkosc obrotowa kol (obrotow na sekunde) double nrot_eps = 0.0; // przyspieszenie kątowe kół (bez kierunku) double const &WheelFlat() const { return wheelFlat; } void SetWheelFlat(double const Value) { wheelFlat = Value; } @@ -961,8 +963,8 @@ class Vehicle double FStand = 0.0; /*! sila pociagowa i oporow ruchu*/ double FTotal = 0.0; /*! calkowita sila dzialajaca na pojazd*/ double Ntotal = 0.0; /*!s siła nacisku klockow*/ - bool SlippingWheels = false; - bool SandDose = false; /*! poslizg kol, sypanie piasku*/ + bool const &SlippingWheels() const { return slippingWheels; } + bool const &SandDose() const { return sandDose; } /*! poslizg kol, sypanie piasku*/ bool SandDoseManual = false; /*piaskowanie reczne*/ bool SandDoseAuto = false; /*piaskowanie automatyczne*/ bool SandDoseAutoAllow = true; /*zezwolenie na automatyczne piaskowanie*/ @@ -977,11 +979,11 @@ class Vehicle bool GensetSelected() const { return TractionMode == traction_mode::genset; } water_pump WaterPump; water_heater WaterHeater; - bool WaterCircuitsLink{false}; // optional connection between water circuits + bool const &WaterCircuitsLink() const { return waterCircuitsLink; } // optional connection between water circuits ByEnd MotorBlowers; door_data Doors; float DoorsOpenWithPermitAfter{-1.f}; // remote open if permit button is held for specified time. NOTE: separate from door data as its cab control thing - int DoorsPermitLightBlinking{0}; // when the doors permit signal light is blinking + int const &DoorsPermitLightBlinking() const { return doorsPermitLightBlinking; } // when the doors permit signal light is blinking /* */ @@ -1020,17 +1022,17 @@ class Vehicle void SetLightsPos(int const Value) { lightsPos = Value; } int DirActive = 0; // czy lok. jest wlaczona i w ktorym kierunku: względem wybranej kabiny: -1 - do tylu, +1 - do przodu, 0 - wylaczona int DirAbsolute = 0; // zadany kierunek jazdy względem sprzęgów (1=w strone 0,-1=w stronę 1) - int MainCtrlMaxDirChangePos{0}; // can't change reverser state with master controller set above this position + int const &MainCtrlMaxDirChangePos() const { return mainCtrlMaxDirChangePos; } // can't change reverser state with master controller set above this position int CabActive = 0; // numer kabiny, z której jest sterowanie: 1 lub -1; w przeciwnym razie brak sterowania - rozrzad int const &CabOccupied() const { return cabOccupied; } // numer kabiny, w ktorej jest obsada (zwykle jedna na skład) // TODO: move to TController void SetCabOccupied(int const Value) { cabOccupied = Value; } - bool CabMaster = false; // czy pojazd jest nadrzędny w składzie + bool const &CabMaster() const { return cabMaster; } // 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}; + bool const &PulleeMode() const { return pulleeMode; } inline bool IsCabMaster() const { - return CabActive == cabOccupied && CabMaster; + return CabActive == cabOccupied && cabMaster; } // czy aktualna kabina jest na pewno tą, z której można sterować bool AutomaticCabActivation = true; // czy zmostkowany rozrzad przelacza sie sam przy zmianie kabiny int InactiveCabFlag = 0; // co sie dzieje przy dezaktywacji kabiny @@ -1058,17 +1060,17 @@ class Vehicle double Mw = 0.0; // sily napedne double Fw = 0.0; - double Ft = 0.0; + double const &Ft() const { return ft; } // Ra: Im jest ujemny, jeśli lok jedzie w stronę sprzęgu 1 // a ujemne powinien być przy odwróconej polaryzacji sieci... // w wielu miejscach jest używane abs(Im) - int Imin = 0; + int const &Imin() const { return imin; } int Imax = 0; /*prad przelaczania automatycznego rozruchu, prad bezpiecznika*/ double EngineVoltage = 0.0; // voltage supplied to engine int MainCtrlActualPos = 0; /*wskaznik RList*/ int ScndCtrlActualPos = 0; /*wskaznik MotorParam*/ - bool DelayCtrlFlag = false; // czy czekanie na 1. pozycji na załączenie? - bool AutoRelayFlag = false; /*mozna zmieniac jesli AutoRelayType=2*/ + bool const &DelayCtrlFlag() const { return delayCtrlFlag; } // czy czekanie na 1. pozycji na załączenie? + bool const &AutoRelayFlag() const { return autoRelayFlag; } /*mozna zmieniac jesli autoRelayType=2*/ bool FuseFlag = false; /*!o bezpiecznik nadmiarowy*/ double LouvresOpenPressure{5.0}; // main reservoir pressure [bar] at which the pneumatic louvres of the motor fans open (ET22) bool ResistorsFlag = false; /*!o jazda rezystorowa*/ @@ -1084,15 +1086,15 @@ class Vehicle double eimic_step_progress{0.0}; // the part of the next UniCtrlValStep the controller has covered so far double eim_localbrake = 0; /*nastawa hamowania dodatkowego pneumatycznego lokomotywy*/ int EIMCtrlType = 0; /*rodzaj wariantu zadajnika jazdy*/ - bool SpeedCtrlTypeTime = false; /*czy tempomat sterowany czasowo*/ + bool const &SpeedCtrlTypeTime() const { return speedCtrlTypeTime; } /*czy tempomat sterowany czasowo*/ int SpeedCtrlAutoTurnOffFlag = 0; /*czy tempomat sam się wyłącza*/ bool EIMCtrlAdditionalZeros = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ - bool EIMCtrlEmergency = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ - bool EIMCtrlMainEmergency = false; /*czy zadajnik typu 2 (Elf) ma pozycje hamowania naglego ponizej swojej pozycji 0*/ + bool const &EIMCtrlEmergency() const { return eimCtrlEmergency; } /*czy ma dodatkowe zero jazdy i zero hamowania */ + bool const &EIMCtrlMainEmergency() const { return eimCtrlMainEmergency; } /*czy zadajnik typu 2 (Elf) ma pozycje hamowania naglego ponizej swojej pozycji 0*/ double SpeedCtrlTimer = 0; /*zegar dzialania tempomatu z wybieralna predkoscia*/ - double eimicSpeedCtrl = 1; /*pozycja sugerowana przez tempomat*/ + double const &eimicSpeedCtrl() const { return eimicSpeedCtrlValue; } /*pozycja sugerowana przez tempomat*/ double eimicSpeedCtrlIntegral = 0; /*calkowany blad ustawienia predkosci*/ - double NewSpeed = 0; /*nowa predkosc do zadania*/ + double const &NewSpeed() const { return newSpeed; } /*nowa predkosc do zadania*/ /*-zmienne dla drezyny*/ double PulseForce = 0.0; /*przylozona sila*/ @@ -1100,7 +1102,7 @@ class Vehicle int PulseForceCount = 0; /*dla drezyny, silnika spalinowego i parowego*/ - double eAngle = M_PI * 0.5; + double const &eAngle() const { return eAngleValue; } /*-dla wagonow*/ float const &LoadAmount() const { return loadAmount; } /*masa w T lub ilosc w sztukach - zaladowane*/ @@ -1137,7 +1139,7 @@ class Vehicle int DoubleTr = 1; // trakcja ukrotniona - przedni pojazd 'Winger 160304 basic_light CompartmentLights; - bool PhysicActivation = true; + bool const &PhysicActivation() const { return physicActivation; } // what the brake force (Fb) came from when the physics fell asleep (switch_physics()), for the test of ComputeTotalForce(): // asleep, a vehicle keeps the Fb and FStand of its last step, and a change of these wakes it struct @@ -1152,7 +1154,7 @@ class Vehicle double FrictConst1 = 0.0; double FrictConst2s = 0.0; double FrictConst2d = 0.0; - double TotalMassxg = 0.0; /*TotalMass*g*/ + double TotalMassxg = 0.0; /*totalMass*g*/ int iProblem = 0; // flagi problemów z taborem, aby AI nie musiało porównywać; 0=może jechać // the lights switched on at each end (light::), from which the current they draw is counted @@ -1181,7 +1183,7 @@ class Vehicle void SetDimmerPosition(int const Value) { modernDimmerPosition = Value; } int modernDimmerDefaultPosition{0}; // bool modernContainOffPos{true}; - bool enableModernDimmer{false}; + bool const &enableModernDimmer() const { return enableModernDimmerValue; } bool modernDimmerCanCycle{false}; // the given dimmer position brought into the DimmerList, to its first or last entry; 0 for an empty list int clampDimmerPosition(int Position) const; @@ -1204,12 +1206,12 @@ class Vehicle plc::basic_controller m_plc; - int AIHintPantstate{0}; // suggested pantograph setup + int const &AIHintPantstate() const { return aiHintPantstate; } // suggested pantograph setup // suggested pantograph setup in shunting (AI: ShuntPantstate=, eu07/maszyna#461), the bits as in Pantstate: 1 front, // 2 rear, 3 both; 0 (the default) shunts with the pantographs handled as in train mode - int AIHintShuntPantstate{0}; + int const &AIHintShuntPantstate() const { return aiHintShuntPantstate; } bool AIHintPantUpIfIdle{true}; // whether raise both pantographs if idling for a while - double AIHintLocalBrakeAccFactor{1.05}; // suggested acceleration weight for local brake operation + double const &AIHintLocalBrakeAccFactor() const { return aiHintLocalBrakeAccFactor; } // suggested acceleration weight for local brake operation Vehicle(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab); // obsługa sprzęgów @@ -1260,9 +1262,9 @@ class Vehicle // 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}; + derail_motion::cause const &DerailCause() const { return derailCause; } + double const &DerailAcceleration() const { return derailAcceleration; } + int const &DerailSide() const { return derailSide; } // 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; @@ -1279,9 +1281,9 @@ class Vehicle double buffer_height_at(VehicleEnd 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}; + DerailReason const &CollisionDerail() const { return collisionDerail; } // physics.collisions monitor: how many crushes the log told of, of the hits of this vehicle on the others - int crush_reports{0}; + int const &crush_reports() const { return crushreportsValue; } // 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 @@ -1860,6 +1862,60 @@ class Vehicle std::optional LightsPresetCabLight(int Position) const; private: + // what the vehicle works out or is defined with, which the rest of the simulator only reads + double vmax = -1.0; + train_type trainType{train_type::generic}; + double totalMass = 0.0; + double ft = 0.0; + int scndCtrlPosNo = 0; + bool slippingWheels = false; + int nAxles = 0; + bool speedCtrl = false; + double nrotValue = 0.0; + double aDist = 0.0; + bool sandDose = false; + float wheelDiameter = 1.f; + DerailReason collisionDerail{NONE}; + bool autoRelayFlag = false; + double bDist = 0.0; + bool physicActivation = true; + bool waterCircuitsLink{false}; + bool enableModernDimmerValue{false}; + double mred = 0.0; + bool delayCtrlFlag = false; + int crushreportsValue{0}; + bool epFuse = true; + int imaxHi = 0; + double initialCtrlDelay = 0.0; + double accSVBased{}; + derail_motion::cause derailCause{derail_motion::cause::off_rails}; + int nPoweredAxles = 0; + bool motorOverloadRelayHighThreshold{false}; + int doorsPermitLightBlinking{0}; + int mainCtrlMaxDirChangePos{0}; + double derailAcceleration{0.0}; + int derailmentreportsValue = 0; + bool cabMaster = false; + bool pulleeMode{false}; + int imin = 0; + bool speedCtrlTypeTime = false; + bool eimCtrlEmergency = false; + double eimicSpeedCtrlValue = 1; + double newSpeed = 0; + int aiHintPantstate{0}; + double uniCtrlValStep{0.0}; + int imaxLo = 0; + int autoRelayType = 0; + bool fieldShuntSwitch = false; + int aiFlag{0}; + bool eimCtrlMainEmergency = false; + double eAngleValue = M_PI * 0.5; + int aiHintShuntPantstate{0}; + double aiHintLocalBrakeAccFactor{1.05}; + int derailSide{0}; + horn_supply hornSupply{horn_supply::air}; + bool uniCtrlIntegratedLocalBrakeCtrl = false; + double windingRes = 0.0; // the switches and the controllers the cab, the AI and the scenery change only through the operations above double travelSpeed = 0.0; TLocation location{0.0, 0.0, 0.0}; diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 48749f3ff..2178bcb22 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -76,7 +76,7 @@ std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle cons return on(Occupied.lowVoltage.IsBatteryOn() || Controlling.lowVoltage.IsBatteryOn(), device::battery) | on(Controlling.lineBreaker.IsClosed(), device::main_breaker) | on(Controlling.pantographs[VehicleEnd::front].is_active, device::pantograph_front) | on(Controlling.pantographs[VehicleEnd::rear].is_active, device::pantograph_rear) | on(Controlling.converter.IsRunning(), device::converter) | on(Controlling.air.compressor.IsRunning(), device::compressor) | on(Controlling.lineContactors.IsClosed(), device::line_contactors) | - on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose, device::sanding) | on(Occupied.WarningSignal() != 0, device::horn) | + on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose(), device::sanding) | on(Occupied.WarningSignal() != 0, device::horn) | on(false == Occupied.Doors.instances[VehicleSide::left].is_closed, device::doors_left) | on(false == Occupied.Doors.instances[VehicleSide::right].is_closed, device::doors_right) | on(Occupied.Radio(), device::radio) | on(Controlling.trainHeating.IsOn(), device::heating) | on(Occupied.brakes.spring.isActive, device::spring_brake) | on(Controlling.ShuntMode, device::shunt_mode) | @@ -87,7 +87,7 @@ std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle cons on(Occupied.brakes.distributor != nullptr && Occupied.brakes.distributor->Releaser(), device::brake_releaser) | on(Controlling.FuelPump.is_active, device::fuel_pump) | on(Controlling.OilPump.is_active, device::oil_pump) | on(Controlling.MotorBlowers[VehicleEnd::front].is_active || Controlling.MotorBlowers[VehicleEnd::rear].is_active, device::motor_blowers) | - on(Controlling.diesel.heat.engine_is_hot, device::engine_hot) | on(Controlling.SpeedCtrl && Controlling.SpeedCtrlUnit.IsActive, device::speed_control); + on(Controlling.diesel.heat.engine_is_hot, device::engine_hot) | on(Controlling.SpeedCtrl() && Controlling.SpeedCtrlUnit.IsActive, device::speed_control); } std::uint8_t engine_of(physics::Vehicle const &Physics) { @@ -431,7 +431,7 @@ void blackbox_recorder::write_cab() { // the vehicle itself, if none in the unit is powered auto const *powered{train->Dynamic()->FindPowered()}; auto const facing{powered->DirectionGet() * vehicle->DirectionGet()}; - sample.wheel_speed_kmh = static_cast(facing * M_PI * powered->physics->WheelDiameter * powered->physics->nrot * 3.6); + sample.wheel_speed_kmh = static_cast(facing * M_PI * powered->physics->WheelDiameter() * powered->physics->nrot() * 3.6); sample.acceleration = static_cast(controlling->AccS()); sample.lateral_acceleration = static_cast(occupied->AccN()); if (owner != nullptr && owner->is_train()) { @@ -445,7 +445,7 @@ void blackbox_recorder::write_cab() { sample.driving = driver_of(*vehicle); sample.flags = (FreeFlyModeFlag ? 0 : blackbox::cab_flags::in_cab) | (owner != nullptr && owner->is_active() ? blackbox::cab_flags::ai_valid : 0) | (controlling->SecuritySystem.is_blinking() ? blackbox::cab_flags::alerter_blinking : 0) | - (controlling->SecuritySystem.is_beeping() ? blackbox::cab_flags::alerter_beeping : 0) | (controlling->SlippingWheels ? blackbox::cab_flags::wheel_slip : 0) | + (controlling->SecuritySystem.is_beeping() ? blackbox::cab_flags::alerter_beeping : 0) | (controlling->SlippingWheels() ? blackbox::cab_flags::wheel_slip : 0) | (occupied->RadioStopFlag() ? blackbox::cab_flags::radio_stop : 0) | (occupied->brakes.alarmChain ? blackbox::cab_flags::alarm_chain : 0); sample.main_controller = static_cast(controlling->MainCtrlPos()); sample.scnd_controller = static_cast(controlling->ScndCtrlPos()); @@ -483,7 +483,7 @@ void blackbox_recorder::write_cab() { sample.water_temperature = controlling->diesel.heat.Twy; sample.oil_temperature = controlling->diesel.heat.To; sample.engine_temperature = controlling->diesel.heat.Ts; - sample.speed_control_kmh = controlling->SpeedCtrl ? static_cast(controlling->SpeedCtrlUnit.DesiredVelocity) : 0.0f; + sample.speed_control_kmh = controlling->SpeedCtrl() ? static_cast(controlling->SpeedCtrlUnit.DesiredVelocity) : 0.0f; sample.engine_power = static_cast(controlling->EnginePower); sample.hand_brake = static_cast(std::clamp(occupied->brakes.HandBrakePosition(), -128, 127)); sample.brake_mode = static_cast(occupied->brakes.operatingMode); diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index 339b85e00..524a9e39a 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -108,7 +108,7 @@ void prepare_diesel(driven const &Driven) { // the pantographs' own air topped up by their compressor, and the pantographs raised void raise_pantographs(driven const &Driven) { auto &pantographs{Driven.pantographs}; - if (auto const enough{(pantographs.TrainType == train_type::emu ? 2.5 : 3.5) + 0.1}; pantographs.pantographAir.Pressure() < enough) { + if (auto const enough{(pantographs.TrainType() == train_type::emu ? 2.5 : 3.5) + 0.1}; pantographs.pantographAir.Pressure() < enough) { if (false == pantographs.pantographAir.config.autoValve) { pantographs.pantographAir.ConnectToMainReservoir(false); // the pantographs on their own air } @@ -149,7 +149,7 @@ void switch_auxiliaries_on(physics::Vehicle &Cab) { Cab.MotorBlowersSwitch(true, side); } } - if (Cab.EngineType == TEngineType::DieselElectric && fieldshunting::has_switch(Cab.AutoRelayType, Cab.FieldShuntSwitch)) { + if (Cab.EngineType == TEngineType::DieselElectric && fieldshunting::has_switch(Cab.AutoRelayType(), Cab.FieldShuntSwitch())) { Cab.AutoRelaySwitch(true); } } diff --git a/tests/unit/figures.cpp b/tests/unit/figures.cpp index ce086154c..bb3483dff 100644 --- a/tests/unit/figures.cpp +++ b/tests/unit/figures.cpp @@ -88,7 +88,7 @@ void figures::sample(double Time, physics::Vehicle const &Vehicle) { } part.cylinders_peak = std::max(part.cylinders_peak, Vehicle.brakes.cylinderPressure); part.current_peak = std::max(part.current_peak, std::abs(Vehicle.Im)); - part.force_peak = std::max(part.force_peak, std::abs(Vehicle.Ft) / 1000.0); + part.force_peak = std::max(part.force_peak, std::abs(Vehicle.Ft()) / 1000.0); m_last_time = Time; m_last_speed = speed; @@ -98,7 +98,7 @@ void figures::sample(double Time, physics::Vehicle const &Vehicle) { m_piped |= pipe >= 0.1; m_braked |= Vehicle.brakes.cylinderPressure >= 0.005; m_current |= std::abs(Vehicle.Im) >= 0.5; - m_force |= std::abs(Vehicle.Ft) >= 50.0; + m_force |= std::abs(Vehicle.Ft()) >= 50.0; } void figures::mark(std::string const &Event) { diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index 429349288..1210a7354 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -45,11 +45,11 @@ std::vector motion() { {"V", [](auto const &M) { return M.V(); }}, {"DistCounter", [](auto const &M) { return M.DistCounter(); }}, {"AccS", [](auto const &M) { return M.AccS(); }}, - {"nrot", [](auto const &M) { return M.nrot; }}, - {"Ft", [](auto const &M) { return M.Ft; }}, + {"nrot", [](auto const &M) { return M.nrot(); }}, + {"Ft", [](auto const &M) { return M.Ft(); }}, {"Fb", [](auto const &M) { return M.Fb; }}, {"FStand", [](auto const &M) { return M.FStand; }}, - {"SlippingWheels", [](auto const &M) { return M.SlippingWheels ? 1.0 : 0.0; }}, + {"SlippingWheels", [](auto const &M) { return M.SlippingWheels() ? 1.0 : 0.0; }}, }; } @@ -126,25 +126,25 @@ std::vector doors() { std::vector parameters() { std::vector result{ {"CategoryFlag", [](auto const &M) { return M.CategoryFlag; }}, - {"TrainType", [](auto const &M) { return legacy_code(M.TrainType); }}, + {"TrainType", [](auto const &M) { return legacy_code(M.TrainType()); }}, {"EngineType", [](auto const &M) { return static_cast(M.EngineType); }}, - {"Vmax", [](auto const &M) { return M.Vmax; }}, + {"Vmax", [](auto const &M) { return M.Vmax(); }}, {"Mass", [](auto const &M) { return M.Mass; }}, - {"TotalMass", [](auto const &M) { return M.TotalMass; }}, - {"Mred", [](auto const &M) { return M.Mred; }}, + {"TotalMass", [](auto const &M) { return M.TotalMass(); }}, + {"Mred", [](auto const &M) { return M.Mred(); }}, {"Power", [](auto const &M) { return M.Power; }}, {"HeatingPower", [](auto const &M) { return M.trainHeating.config.power; }}, {"LightPower", [](auto const &M) { return M.LightPower; }}, {"BatteryVoltage", [](auto const &M) { return M.lowVoltage.BatteryVoltage(); }}, {"Cx", [](auto const &M) { return M.Cx; }}, - {"WheelDiameter", [](auto const &M) { return M.WheelDiameter; }}, + {"WheelDiameter", [](auto const &M) { return M.WheelDiameter(); }}, {"TrackW", [](auto const &M) { return M.TrackW; }}, {"AxleInertialMoment", [](auto const &M) { return M.AxleInertialMoment; }}, - {"NPoweredAxles", [](auto const &M) { return M.NPoweredAxles; }}, - {"NAxles", [](auto const &M) { return M.NAxles; }}, + {"NPoweredAxles", [](auto const &M) { return M.NPoweredAxles(); }}, + {"NAxles", [](auto const &M) { return M.NAxles(); }}, {"BearingType", [](auto const &M) { return M.BearingType; }}, - {"ADist", [](auto const &M) { return M.ADist; }}, - {"BDist", [](auto const &M) { return M.BDist; }}, + {"ADist", [](auto const &M) { return M.ADist(); }}, + {"BDist", [](auto const &M) { return M.BDist(); }}, {"NBpA", [](auto const &M) { return M.brakes.config.blocksPerAxle; }}, {"SandCapacity", [](auto const &M) { return M.SandCapacity; }}, {"BrakeSystem", [](auto const &M) { return static_cast(M.brakes.config.kind); }}, @@ -179,13 +179,13 @@ std::vector parameters() { {"AirLeakRate", [](auto const &M) { return M.air.config.leakRate; }}, {"BrakeCtrlPosNo", [](auto const &M) { return M.brakes.config.handlePositions; }}, {"MainCtrlPosNo", [](auto const &M) { return M.MainCtrlPosNo; }}, - {"ScndCtrlPosNo", [](auto const &M) { return M.ScndCtrlPosNo; }}, + {"ScndCtrlPosNo", [](auto const &M) { return M.ScndCtrlPosNo(); }}, {"LightsPosNo", [](auto const &M) { return M.LightsPosNo; }}, {"MBrake", [](auto const &M) { return M.brakes.config.hasHandBrake ? 1.0 : 0.0; }}, {"StopBrakeDecc", [](auto const &M) { return M.brakes.holding.deceleration; }}, {"BrakeDelays", [](auto const &M) { return M.brakes.config.availableDelays; }}, {"BrakeOpModes", [](auto const &M) { return M.brakes.config.availableOperatingModes; }}, - {"Imin", [](auto const &M) { return M.Imin; }}, + {"Imin", [](auto const &M) { return M.Imin(); }}, {"Imax", [](auto const &M) { return M.Imax; }}, {"EIMCtrlType", [](auto const &M) { return M.EIMCtrlType; }}, {"Volume", [](auto const &M) { return M.brakes.reservoirAir; }}, diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index 39c7049d2..5075299a9 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -41,12 +41,12 @@ std::vector const &invariants() { static std::vector const rules{ {"every value a number", [](auto const &M, double, auto const *) { - std::initializer_list const values{M.V(), M.AccS(), M.Ft, M.Fb, M.Im, M.Itot, M.EngineVoltage, + std::initializer_list const values{M.V(), M.AccS(), M.Ft(), M.Fb, M.Im, M.Itot, M.EngineVoltage, M.enrot, M.brakePipe.Pressure(), M.brakes.cylinderPressure, M.brakes.independentCylinderPressure, M.mainPipe.Pressure(), M.air.MainReservoirPressure(), M.lowVoltage.BatteryVoltage()}; return std::ranges::all_of(values, [](double const Value) { return std::isfinite(Value); }); }, [](auto const &M) { - return values({{"V", M.V()}, {"AccS", M.AccS()}, {"Ft", M.Ft}, {"Fb", M.Fb}, {"Im", M.Im}, {"Itot", M.Itot}, {"EngineVoltage", M.EngineVoltage}, + return values({{"V", M.V()}, {"AccS", M.AccS()}, {"Ft", M.Ft()}, {"Fb", M.Fb}, {"Im", M.Im}, {"Itot", M.Itot}, {"EngineVoltage", M.EngineVoltage}, {"enrot", M.enrot}, {"PipePress", M.brakePipe.Pressure()}, {"BrakePress", M.brakes.cylinderPressure}, {"LocBrakePress", M.brakes.independentCylinderPressure}, {"ScndPipePress", M.mainPipe.Pressure()}, {"Compressor", M.air.MainReservoirPressure()}, {"BatteryVoltage", M.lowVoltage.BatteryVoltage()}}); }}, @@ -81,8 +81,8 @@ std::vector const &invariants() { return values({{"StLinFlag", M.lineContactors.IsClosed()}, {"DynamicBrakeFlag", M.brakes.electrodynamic.on}, {"Im", M.Im}, {"MainCtrlActualPos", M.MainCtrlActualPos}}); }}, {"no tractive force without power", - [](auto const &M, double, auto const *) { return M.Power >= 0.01 || std::abs(M.Ft) < 1.0; }, - [](auto const &M) { return values({{"Power", M.Power}, {"Ft", M.Ft}}); }}, + [](auto const &M, double, auto const *) { return M.Power >= 0.01 || std::abs(M.Ft()) < 1.0; }, + [](auto const &M) { return values({{"Power", M.Power}, {"Ft", M.Ft()}}); }}, {"engine fill between none and full", [](auto const &M, double, auto const *) { return M.diesel.fill >= 0.0 && M.diesel.fill <= 1.0; }, [](auto const &M) { return values({{"dizel_fill", M.diesel.fill}}); }}, diff --git a/tests/unit/test_6dg_power_steps.cpp b/tests/unit/test_6dg_power_steps.cpp index c2ca18274..5f3d8ce4e 100644 --- a/tests/unit/test_6dg_power_steps.cpp +++ b/tests/unit/test_6dg_power_steps.cpp @@ -100,7 +100,7 @@ TEST_CASE("6Dg: the shipped definition sets the controller's power demand in ste 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)); + 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}; @@ -180,7 +180,7 @@ TEST_CASE("6Dg: the diesel-electric drive follows the stepped demand") { 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())); + 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 @@ -200,7 +200,7 @@ TEST_CASE("6Dg: the diesel-electric drive follows the stepped demand") { 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); + REQUIRE(loco->UniCtrlValStep() == 0.0); get_ready(loco, line); // a tap moves it by 0.01 only tap(loco, raise, line); diff --git a/tests/unit/test_ai_hints.cpp b/tests/unit/test_ai_hints.cpp index d01e421c9..e23a9bf36 100644 --- a/tests/unit/test_ai_hints.cpp +++ b/tests/unit/test_ai_hints.cpp @@ -10,8 +10,8 @@ using test::vehicle; TEST_CASE("ai hints: without the AI section the pantographs follow the built-in logic") { vehicle wagon{definition::load("wagon")}; - CHECK(wagon->AIHintPantstate == 0); - CHECK(wagon->AIHintShuntPantstate == 0); + CHECK(wagon->AIHintPantstate() == 0); + CHECK(wagon->AIHintShuntPantstate() == 0); CHECK(wagon->AIHintPantUpIfIdle); } @@ -19,13 +19,13 @@ TEST_CASE("ai hints: the suggested pantograph setup for shunting is read apart f // eu07/maszyna#461: so the ET41 doesn't shunt with all of its four pantographs up vehicle shunting{definition::load("wagon").set("AI", "Pantstate", 1).set("AI", "ShuntPantstate", 2)}; - CHECK(shunting->AIHintPantstate == 1); - CHECK(shunting->AIHintShuntPantstate == 2); + CHECK(shunting->AIHintPantstate() == 1); + CHECK(shunting->AIHintShuntPantstate() == 2); } TEST_CASE("ai hints: a .fiz with the setup for train mode only has none for shunting") { vehicle train{definition::load("wagon").set("AI", "Pantstate", 3)}; - CHECK(train->AIHintPantstate == 3); - CHECK(train->AIHintShuntPantstate == 0); + CHECK(train->AIHintPantstate() == 3); + CHECK(train->AIHintShuntPantstate() == 0); } diff --git a/tests/unit/test_brakes.cpp b/tests/unit/test_brakes.cpp index e83c25334..d4dae6f50 100644 --- a/tests/unit/test_brakes.cpp +++ b/tests/unit/test_brakes.cpp @@ -167,14 +167,14 @@ TEST_CASE("brakes: a wagon standing braked on a gradient sleeps while the brakes wagon.run(30.0, slope); REQUIRE(wagon->brakes.cylinderPressure > 1.0); CHECK(std::abs(wagon.speed()) < 0.01); - CHECK_FALSE(wagon->PhysicActivation); + CHECK_FALSE(wagon->PhysicActivation()); // the brakes holding as they are, it sleeps on auto wakes{0}; for (int step = 0; step < 12000; ++step) { - auto const asleep{false == wagon->PhysicActivation}; + auto const asleep{false == wagon->PhysicActivation()}; wagon.step(slope); - if (asleep && wagon->PhysicActivation) { + if (asleep && wagon->PhysicActivation()) { ++wakes; } } @@ -187,7 +187,7 @@ TEST_CASE("brakes: a wagon standing braked on a gradient sleeps while the brakes CHECK(wagon->brakes.cylinderPressure < 0.1); CHECK(wagon->Fb < 1.0); CHECK(std::abs(wagon.speed()) > 1.0); - CHECK(wagon->PhysicActivation); + CHECK(wagon->PhysicActivation()); } TEST_CASE("brakes: a wagon held by its hand brake on a gradient wakes and rolls away once the hand brake is released") { @@ -202,7 +202,7 @@ TEST_CASE("brakes: a wagon held by its hand brake on a gradient wakes and rolls wagon.run(90.0, slope); REQUIRE(wagon->brakes.cylinderPressure < 0.1); CHECK(std::abs(wagon.speed()) < 0.01); - CHECK_FALSE(wagon->PhysicActivation); + CHECK_FALSE(wagon->PhysicActivation()); wagon->DecManualBrakeLevel(ManualBrakePosNo); wagon.run(30.0, slope); diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index b87c1576e..5cf01117f 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -74,7 +74,7 @@ TEST_CASE("cab: the engine's idle speed, and the ET42's second controller shown CHECK(et42->GetVirtualScndPos() == 1); // with a speed control in place of the second controller, either end of it, for the AI vehicle railbus{definition::fiz("21xm_v1/214ma")}; - REQUIRE(railbus->SpeedCtrl); + REQUIRE(railbus->SpeedCtrl()); railbus->SetScndCtrlPos(1); CHECK(railbus->IsScndCtrlNoPowerPos()); CHECK(railbus->IsScndCtrlMaxPowerPos()); @@ -167,11 +167,11 @@ TEST_CASE("cab: damaged motors cut off in a car without a driver") { driven->DamageFlag |= VehicleDamage::engine; CHECK_FALSE(driven->CutOffEngine()); vehicle car{definition::fiz("ew58_v1/ew58-sa")}; - auto const axles{car->NPoweredAxles}; + auto const axles{car->NPoweredAxles()}; CHECK_FALSE(car->CutOffEngine()); car->DamageFlag |= VehicleDamage::engine; CHECK(car->CutOffEngine()); - CHECK(car->NPoweredAxles == axles / 2); + CHECK(car->NPoweredAxles() == axles / 2); CHECK_FALSE(car->DamageFlag.HasAll(VehicleDamage::engine)); vehicle wagon{definition::fiz("3wl_v2/3wl")}; wagon->DamageFlag |= VehicleDamage::engine; diff --git a/tests/unit/test_cntrl.cpp b/tests/unit/test_cntrl.cpp index 017bc0ee6..428381092 100644 --- a/tests/unit/test_cntrl.cpp +++ b/tests/unit/test_cntrl.cpp @@ -22,7 +22,7 @@ TEST_CASE("cntrl: the brake delays of the settings come from BDelay1 to BDelay4" TEST_CASE("cntrl: the relays of a multiple unit start on their own, of other vehicles by hand") { SUBCASE("multiple unit") { vehicle unit{definition::load("wagon").set("Param", "Type", "ezt")}; - REQUIRE(unit->TrainType == train_type::emu); + REQUIRE(unit->TrainType() == train_type::emu); CHECK(unit->protection.config.groundStart == start_t::automatic); CHECK(unit->converter.config.overloadRelayStart == start_t::converter); // activates when the converter is switched off } @@ -64,7 +64,7 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and CAPTURE(path); vehicle locked{definition::fiz(path).set("Cntrl", "ScndCtrlResistiveLock", "Yes"), 0.0, "test", 1}; REQUIRE(locked->ScndCtrlResistiveLock); - REQUIRE(locked->ScndCtrlPosNo > 0); + REQUIRE(locked->ScndCtrlPosNo() > 0); auto const resistancefree{resistance_free_position(locked.physics())}; REQUIRE(resistancefree > 1); if (resistancefree <= 1) { @@ -117,7 +117,7 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and SUBCASE("the master controller taken back from a shunt step drops the shunt") { controllers_at(locked, resistancefree); REQUIRE(locked->IncScndCtrl(1)); - if (locked->TrainType == train_type::et22) { + if (locked->TrainType() == train_type::et22) { // the ET22's master controller doesn't turn with the shunt on: the shunt goes off first, as before CHECK_FALSE(locked->DecMainCtrl(1)); CHECK(locked->MainCtrlPos() == resistancefree); @@ -152,7 +152,7 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and controllers_at(locked, lastseries); locked->DirActive = 1; REQUIRE(locked->IncScndCtrl(1)); - if (locked->TrainType == train_type::et22) { + if (locked->TrainType() == train_type::et22) { CHECK_FALSE(locked->IncMainCtrl(1)); // the ET22's interlock, as before CHECK(locked->ScndCtrlPos() == 1); } diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index eadd5732f..f4222beac 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -180,10 +180,10 @@ crash_outcome freight_crash(double const Speed, double const Radius, double cons 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.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"); + 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)); @@ -219,7 +219,7 @@ double capacity_of(physics::Vehicle const &First, VehicleEnd const FirstEnd, phy // the kinetic energy of the relative motion of two vehicles closing in at the velocity [J] double relative_energy(physics::Vehicle const &First, physics::Vehicle const &Second, double const Velocity) { - auto const mass{First.TotalMass * Second.TotalMass / (First.TotalMass + Second.TotalMass)}; + auto const mass{First.TotalMass() * Second.TotalMass() / (First.TotalMass() + Second.TotalMass())}; return 0.5 * mass * Velocity * Velocity; } @@ -253,11 +253,11 @@ definition coach(double const 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(physics::Vehicle const &Vehicle, VehicleEnd 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.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; + 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 == VehicleEnd::front ? -1.0 : 1.0) * Vehicle.Couplers[End].CForce); end.other_length = OtherLength; @@ -473,11 +473,11 @@ TEST_CASE("collisions: an empty two-axle wagon between loaded ones in a curve of 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.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; + 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; @@ -502,11 +502,11 @@ TEST_CASE("collisions: an empty two-axle wagon between loaded ones in a curve of // the loaded wagon, four axles, takes it cl::pushed_vehicle heavy; - heavy.mass = loaded->TotalMass - loaded->Mred + 59.5e3; - heavy.axles = loaded->NAxles; + 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; + heavy.pivots = loaded->BDist(); + heavy.axle_base = loaded->ADist(); end.force = 600.0e3; CHECK(cl::pushed_ratio(heavy, end, 150.0) < 0.5); @@ -613,7 +613,7 @@ TEST_CASE("collisions: a locomotive at its starting effort against a braked trai REQUIRE(worst >= derailment::climbing_limit); CHECK(rolled < 0.5); CHECK_FALSE(derailed(empty.physics())); - CHECK(empty->CollisionDerail == NONE); + 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") { @@ -668,9 +668,9 @@ TEST_CASE("collisions: a train propelling an empty wagon into a braked one in a } auto const start{empty->DistCounter()}; train.run(10.0, curve); - MESSAGE(std::format("the empty 3WL: derailed {}, {}, rolled {:.2f} m", derailed(empty.physics()), empty->CollisionDerail == COLLISION_PUSHED_OFF ? "pushed off" : "not pushed off", + MESSAGE(std::format("the empty 3WL: derailed {}, {}, rolled {:.2f} m", derailed(empty.physics()), empty->CollisionDerail() == COLLISION_PUSHED_OFF ? "pushed off" : "not pushed off", (empty->DistCounter() - start) * 1000.0)); - CHECK(empty->CollisionDerail == COLLISION_PUSHED_OFF); + CHECK(empty->CollisionDerail() == COLLISION_PUSHED_OFF); } // ---- recovery @@ -691,7 +691,7 @@ TEST_CASE("collisions: a repaired vehicle has its ends rebuilt and is back on th physics.repair_damage(); CHECK(physics.DamageFlag.Empty()); CHECK(physics.Derailed == derailment::outcome::none); - CHECK(physics.CollisionDerail == NONE); + CHECK(physics.CollisionDerail() == NONE); CHECK(physics.pushed_off_monitor.distance() == 0.0); CHECK(physics.pushed_off_monitor.time() == 0.0); for (auto const &coupler : physics.Couplers) { @@ -723,10 +723,10 @@ TEST_CASE("collisions: the repair of a coupler torn off by the crush rebuilds it 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->CollisionDerail() == COLLISION_PUSHED_OFF); REQUIRE(wagon->Derailed == derailment::outcome::off_rails); wagon->RunCommand(VehicleCommand::setDamage, DamageSet{VehicleDamage::derailed}.Bits(), -1); - CHECK(wagon->CollisionDerail == NONE); + CHECK(wagon->CollisionDerail() == NONE); CHECK(wagon->Derailed == derailment::outcome::none); CHECK_FALSE(wagon->DamageFlag.HasAll(VehicleDamage::derailed)); } @@ -776,7 +776,7 @@ TEST_CASE("collisions: the legacy rule with physics.collisions old, the crush wi else { CHECK(crush == 0.0); } - CHECK(train[0]->crush_reports + train[1]->crush_reports == (model == global_settings::collision_model::monitor ? monitored : 0)); + CHECK(train[0]->crush_reports() + train[1]->crush_reports() == (model == global_settings::collision_model::monitor ? monitored : 0)); } } } @@ -887,8 +887,8 @@ TEST_CASE("collisions: road vehicles keep the legacy rule") { CHECK(derailed(road[0].physics())); CHECK(derailed(road[1].physics())); CHECK(road[0]->Couplers[VehicleEnd::rear].crush == 0.0); - CHECK(road[1]->CollisionDerail == NONE); - CHECK(road[0]->crush_reports + road[1]->crush_reports == 0); + CHECK(road[1]->CollisionDerail() == NONE); + CHECK(road[0]->crush_reports() + road[1]->crush_reports() == 0); } } @@ -900,10 +900,10 @@ TEST_CASE("collisions: a vehicle off the rails by the new model stays in the cha auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 10.0, 0.5)}; wagon->derail_in_collision(COLLISION_PUSHED_OFF, "for the test"); REQUIRE(derailed(wagon.physics())); - auto const before{wagon->TotalMass * wagon->V() + locomotive->TotalMass * locomotive->V()}; + 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()}; + 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); @@ -1136,7 +1136,7 @@ TEST_CASE("collisions: two locomotives (117 t and 84 t) touching at walking spee auto const sm42{definition::fiz("sm42_v1/6d1")}; { vehicle check{su45}; - CHECK(check->TotalMass == doctest::Approx(117.0e3).epsilon(0.02)); + CHECK(check->TotalMass() == doctest::Approx(117.0e3).epsilon(0.02)); } for (auto const physics : {false, true}) { CAPTURE(physics); @@ -1184,8 +1184,8 @@ TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor 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)); + 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); @@ -1208,7 +1208,7 @@ TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor auto &running{train.add(heavy, 0, Coupling::none, 5.0, gap)}; train.run(5.0); CHECK(wall->Couplers[VehicleEnd::rear].crush + running->Couplers[VehicleEnd::front].crush == 0.0); - CHECK(running->CollisionDerail == NONE); + CHECK(running->CollisionDerail() == NONE); } } @@ -1300,14 +1300,14 @@ TEST_CASE("collisions: the monitor goes by the energy of the hit as well") { train.add(definition::fiz("sm42_v1/6d1")); train.add(definition::fiz("su45_v2/301d"), 0, Coupling::none, 5.8, gap); train.run(5.0); - CHECK(train[0]->crush_reports + train[1]->crush_reports == 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::none, 25.0, 20.0); train.run(10.0); - CHECK(train[0]->crush_reports + train[1]->crush_reports == 1); + 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 @@ -1331,12 +1331,12 @@ train_damage damage_of(consist &Train) { for (auto const end : VehicleEnds) { result.energy += vehicle.crush_curve_at(end).energy(0.0, vehicle.Couplers[end].crush); } - result.derailed += vehicle.CollisionDerail != NONE; + result.derailed += vehicle.CollisionDerail() != NONE; if (i + 1 < Train.size()) { result.broken += vehicle.Couplers[VehicleEnd::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" : ""); + 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; @@ -1346,7 +1346,7 @@ train_damage damage_of(consist &Train) { 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(); + energy += 0.5 * Train[i]->TotalMass() * Train[i]->V() * Train[i]->V(); } return energy; } diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index 930893627..b06e4944d 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -39,7 +39,7 @@ std::vector state() { {"WaterPumpDisabled", [](auto const &M) { return flag(M.WaterPump.is_disabled); }}, {"WaterHeaterBreaker", [](auto const &M) { return flag(M.WaterHeater.breaker); }}, {"WaterHeaterEnabled", [](auto const &M) { return flag(M.WaterHeater.is_enabled); }}, - {"WaterCircuitsLink", [](auto const &M) { return flag(M.WaterCircuitsLink); }}, + {"WaterCircuitsLink", [](auto const &M) { return flag(M.WaterCircuitsLink()); }}, {"FuelPumpEnabled", [](auto const &M) { return flag(M.FuelPump.is_enabled); }}, {"FuelPumpDisabled", [](auto const &M) { return flag(M.FuelPump.is_disabled); }}, {"OilPumpEnabled", [](auto const &M) { return flag(M.OilPump.is_enabled); }}, @@ -51,8 +51,8 @@ std::vector state() { {"DirActive", [](auto const &M) { return M.DirActive; }}, {"DirAbsolute", [](auto const &M) { return M.DirAbsolute; }}, {"CabActive", [](auto const &M) { return M.CabActive; }}, - {"CabMaster", [](auto const &M) { return flag(M.CabMaster); }}, - {"AutoRelayFlag", [](auto const &M) { return flag(M.AutoRelayFlag); }}, + {"CabMaster", [](auto const &M) { return flag(M.CabMaster()); }}, + {"AutoRelayFlag", [](auto const &M) { return flag(M.AutoRelayFlag()); }}, {"ConverterAllow", [](auto const &M) { return flag(M.converter.IsAllowed()); }}, {"Battery", [](auto const &M) { return flag(M.lowVoltage.IsBatteryOn()); }}, {"CompressorAllow", [](auto const &M) { return flag(M.air.compressor.IsAllowed()); }}, @@ -62,12 +62,12 @@ std::vector state() { {"DoorRemoteOnly", [](auto const &M) { return flag(M.Doors.remote_only); }}, {"DepartureSignal", [](auto const &M) { return flag(M.DepartureSignal); }}, {"PantsValve", [](auto const &M) { return flag(M.pantographAir.valve.is_enabled) + 2 * flag(M.pantographAir.valve.is_disabled); }}, - {"MaxCurrentHigh", [](auto const &M) { return flag(M.MotorOverloadRelayHighThreshold); }}, - {"Imin", [](auto const &M) { return M.Imin; }}, + {"MaxCurrentHigh", [](auto const &M) { return flag(M.MotorOverloadRelayHighThreshold()); }}, + {"Imin", [](auto const &M) { return M.Imin(); }}, {"DamageFlag", [](auto const &M) { return M.DamageFlag.Bits(); }}, {"RadioStop", [](auto const &M) { return flag(M.RadioStopFlag()); }}, {"BrakeDelayFlag", [](auto const &M) { return M.brakes.delaySetting; }}, - {"SandDose", [](auto const &M) { return flag(M.SandDose); }}, + {"SandDose", [](auto const &M) { return flag(M.SandDose()); }}, {"CabSignal", [](auto const &M) { return flag(M.SecuritySystem.is_cabsignal_blinking()); }}, {"LoadAmount", [](auto const &M) { return M.LoadAmount(); }}, {"LoadStatus", [](auto const &M) { return M.LoadStatus(); }}, diff --git a/tests/unit/test_consist_braking.cpp b/tests/unit/test_consist_braking.cpp index 6b9367407..78859f9db 100644 --- a/tests/unit/test_consist_braking.cpp +++ b/tests/unit/test_consist_braking.cpp @@ -65,7 +65,7 @@ TEST_CASE("consist braking: the full braking position demands the most decelerat CHECK(figures[deceleration] == doctest::Approx(amax)); auto mass_t{0.0}; for (auto const *car : unit.cars) { - mass_t += car->TotalMass * 0.001; + mass_t += car->TotalMass() * 0.001; } CHECK(figures[mass] == doctest::Approx(mass_t)); // the holding brake standing still asks for no more than the service braking does diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index b53f0f904..4f754d0fc 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -259,10 +259,10 @@ TEST_CASE("controls: wheel slip on a slippery track, sand and the anti-slip brak // a notch a second: the controller put to full power at once never gets the line contactors closed scenario.act("full power"); scenario.full_power(0.0); - auto slipped{cab.SlippingWheels}; + auto slipped{cab.SlippingWheels()}; for (int i = 0; i < 10; ++i) { scenario.wait(1.0); - slipped = slipped || cab.SlippingWheels; + slipped = slipped || cab.SlippingWheels(); } // the electric locomotives slip at full power, the SM42, of less power for its weight, doesn't CHECK(slipped == (std::string{path} != "sm42_v1/6d1")); @@ -477,11 +477,11 @@ TEST_CASE("controls: a freight wagon loaded and braked") { CHECK(wagon.AssignLoad(load, 30.f) == (known || std::string{load}.empty())); wagon.ComputeMass(); if (*load == '\0') { - emptymass = wagon.TotalMass; + emptymass = wagon.TotalMass(); } else { // 30 t of a load the wagon takes, none of one it doesn't - CHECK(wagon.TotalMass == doctest::Approx(emptymass + (known ? 30000.0 : 0.0)).epsilon(0.01)); + CHECK(wagon.TotalMass() == doctest::Approx(emptymass + (known ? 30000.0 : 0.0)).epsilon(0.01)); } scenario.start_up(); scenario.get_going(); diff --git a/tests/unit/test_couplers_trains.cpp b/tests/unit/test_couplers_trains.cpp index a98feb802..a98d9bd08 100644 --- a/tests/unit/test_couplers_trains.cpp +++ b/tests/unit/test_couplers_trains.cpp @@ -134,7 +134,7 @@ TEST_CASE("couplers: automatic couplers coupling on contact") { // once coupled, not again until uncoupled; the vehicle which coupled marks it for the AI CHECK_FALSE(first.Couplers[VehicleEnd::rear].AutomaticCouplingAllowed); CHECK_FALSE(second.Couplers[VehicleEnd::front].AutomaticCouplingAllowed); - CHECK((TestFlag(first.AIFlag, sound::attachcoupler) || TestFlag(second.AIFlag, sound::attachcoupler))); + CHECK((TestFlag(first.AIFlag(), sound::attachcoupler) || TestFlag(second.AIFlag(), sound::attachcoupler))); scenario.check(); } } diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp index 4c97ee31e..630941543 100644 --- a/tests/unit/test_crew.cpp +++ b/tests/unit/test_crew.cpp @@ -203,7 +203,7 @@ TEST_CASE("crew: a locomotive under power left by its driver stops and stays bra CHECK(eu07.brakes.HandlePosition() == static_cast(eu07.brakes.driverValve->GetPos(bh_EB))); CHECK(eu07.CabActive == 0); CHECK(eu07.CabOccupied() == 0); - CHECK_FALSE(eu07.CabMaster); + CHECK_FALSE(eu07.CabMaster()); auto const stoppedafter{seconds_to_stop(train, 120.0)}; CAPTURE(stoppedafter); @@ -225,13 +225,13 @@ TEST_CASE("crew: what the AI held is let go when the driver leaves") { cab->signal_departure(true); cab->Sandbox(true); REQUIRE(cab->DepartureSignal); - REQUIRE(cab->SandDose); + REQUIRE(cab->SandDose()); crew::secure(cab.physics(), cab.physics()); CHECK(cab->WarningSignal() == 0); CHECK_FALSE(cab->DepartureSignal); - CHECK_FALSE(cab->SandDose); + CHECK_FALSE(cab->SandDose()); } TEST_CASE("crew: a train left by its driver is braked through the whole of it") { diff --git a/tests/unit/test_definition.cpp b/tests/unit/test_definition.cpp index eeffd49e0..b165b741a 100644 --- a/tests/unit/test_definition.cpp +++ b/tests/unit/test_definition.cpp @@ -10,10 +10,10 @@ TEST_CASE("definition: the wagon from data/wagon.json loads with its values") { vehicle wagon{definition::load("wagon")}; CHECK(wagon->Mass == doctest::Approx(42200.0)); - CHECK(wagon->Vmax == doctest::Approx(120.0)); + CHECK(wagon->Vmax() == doctest::Approx(120.0)); CHECK(wagon->Dim.L == doctest::Approx(26.8)); - CHECK(wagon->WheelDiameter == doctest::Approx(0.96)); - CHECK(wagon->NAxles == 4); + CHECK(wagon->WheelDiameter() == doctest::Approx(0.96)); + CHECK(wagon->NAxles() == 4); CHECK(wagon->brakes.config.maxCylinderPressure[3] == doctest::Approx(3.8)); CHECK(wagon->brakes.config.kind == TBrakeSystem::Pneumatic); } @@ -22,7 +22,7 @@ TEST_CASE("definition: keys set by the test reach the vehicle") { vehicle heavy{definition::load("wagon").set("Param", "M", 60000).set("Wheels", "D", 1.0)}; CHECK(heavy->Mass == doctest::Approx(60000.0)); - CHECK(heavy->WheelDiameter == doctest::Approx(1.0)); + CHECK(heavy->WheelDiameter() == doctest::Approx(1.0)); } TEST_CASE("definition: an unknown test vehicle is an error, not a silently empty one") { @@ -62,7 +62,7 @@ TEST_CASE("definition: lines the loader skips or trims: comments, a hash anywher physics::Vehicle wagon(0.0, "wagon", "test", 0); REQUIRE(wagon.LoadFIZ_Text(crlf)); CHECK(wagon.Mass == doctest::Approx(42200.0)); - CHECK(wagon.Vmax == doctest::Approx(120.0)); + CHECK(wagon.Vmax() == doctest::Approx(120.0)); CHECK(wagon.brakes.config.maxCylinderPressure[3] == doctest::Approx(3.8)); } diff --git a/tests/unit/test_derail_motion.cpp b/tests/unit/test_derail_motion.cpp index 70e6ec810..d114a33ad 100644 --- a/tests/unit/test_derail_motion.cpp +++ b/tests/unit/test_derail_motion.cpp @@ -417,10 +417,10 @@ TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment n eu07vehicle.step(curve); } REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); - CHECK(eu07vehicle->DerailCause == dm::cause::overturned); - CHECK(eu07vehicle->DerailAcceleration > eu07_tipping); + 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); + 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()}; @@ -433,8 +433,8 @@ TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment n 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); + 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}; @@ -443,7 +443,7 @@ TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment n eu07vehicle.step(); REQUIRE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(eu07vehicle->Derailed == dr::outcome::off_rails); - CHECK(eu07vehicle->DerailCause == dm::cause::end_of_track); + 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") { @@ -452,13 +452,13 @@ TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment n pulled->pull_off(-1, 5.0, "test"); CHECK(pulled->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(pulled->Derailed == dr::outcome::off_rails); - CHECK(pulled->DerailCause == dm::cause::pulled_off); - CHECK(pulled->DerailSide == -1); + 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); + CHECK(pulled->DerailCause() == dm::cause::off_rails); + CHECK(pulled->DerailAcceleration() == 0.0); + CHECK(pulled->DerailSide() == 0); } } diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 1dffe2f66..24efb30a8 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -253,13 +253,13 @@ TEST_CASE("derailment: monitor tells again on the same track after a repair") { for (int step = 0; step < 100; ++step) { eu07vehicle.step(curve); } - REQUIRE(eu07vehicle->derailment_reports == 1); + 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); + CHECK(eu07vehicle->derailment_reports() == 2); } TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what the criteria would do") { @@ -277,7 +277,7 @@ TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what t CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); CHECK(eu07vehicle->Derailed == dr::outcome::none); // once on a track, however long it stays over the criteria - CHECK(eu07vehicle->derailment_reports == 1); + CHECK(eu07vehicle->derailment_reports() == 1); REQUIRE(eu07vehicle->derailment_reported.has_value()); CHECK(*eu07vehicle->derailment_reported == &curve.name); // and once more on the next one @@ -286,7 +286,7 @@ TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what t for (int step = 0; step < 100; ++step) { eu07vehicle.step(next); } - CHECK(eu07vehicle->derailment_reports == 2); + CHECK(eu07vehicle->derailment_reports() == 2); CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); SUBCASE("under the criteria nothing is told") { @@ -294,7 +294,7 @@ TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what t for (int step = 0; step < 100; ++step) { slower.step(curve); } - CHECK(slower->derailment_reports == 0); + 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}; diff --git a/tests/unit/test_diesel.cpp b/tests/unit/test_diesel.cpp index 5328c439b..0f49d27f2 100644 --- a/tests/unit/test_diesel.cpp +++ b/tests/unit/test_diesel.cpp @@ -95,7 +95,7 @@ TEST_CASE("diesel: the 214M railbus's torque converter, gears and retarder") { CHECK(railbus.MainCtrlPos() == 5); CHECK(railbus.eimic_real == doctest::Approx(1.0)); CHECK(railbus.torqueConverter.lockedUp); - CHECK(railbus.ScndCtrlActualPos == railbus.ScndCtrlPosNo); + CHECK(railbus.ScndCtrlActualPos == railbus.ScndCtrlPosNo()); struct position { double eimic; bool retarder; @@ -118,7 +118,7 @@ TEST_CASE("diesel: the 214M railbus's torque converter, gears and retarder") { scenario.wait(30.0); CHECK(railbus.Vel == doctest::Approx(0.0)); // the gearbox shifted down as the railbus slowed - CHECK(railbus.ScndCtrlActualPos < railbus.ScndCtrlPosNo); + CHECK(railbus.ScndCtrlActualPos < railbus.ScndCtrlPosNo()); scenario.check(); } @@ -130,7 +130,7 @@ TEST_CASE("diesel: the 214M railbus's speed control, up to the speed of a button scenario.add("21xm_v1/214ma", 1); REQUIRE(scenario.start_up()); auto &railbus{scenario.cab()}; - REQUIRE(railbus.SpeedCtrl); + REQUIRE(railbus.SpeedCtrl()); scenario.get_going(); scenario.full_power(10.0); scenario.act("speed control on"); diff --git a/tests/unit/test_dimmer.cpp b/tests/unit/test_dimmer.cpp index 2368b7ff6..4bfb230ca 100644 --- a/tests/unit/test_dimmer.cpp +++ b/tests/unit/test_dimmer.cpp @@ -63,7 +63,7 @@ TEST_CASE("dimmer: a DefaultPos past the end of the list starts the dimmer at it TEST_CASE("dimmer: without the modern dimmer a DefaultPos past the end of the list puts the dimmer at its last position") { vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed}), 7).set("Switches", "ModernDimmer", "No")}; - REQUIRE_FALSE(cab->enableModernDimmer); + REQUIRE_FALSE(cab->enableModernDimmer()); CHECK(cab->DimmerPosition() == 1); CHECK(cab->currentDimPosition().isDimmed); diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp index 008a8fbe8..d8e6b05c1 100644 --- a/tests/unit/test_dynamic_brake_diesel.cpp +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -85,7 +85,7 @@ TEST_CASE("diesel-electric dynamic brake: none without its definition") { controller_to(locomotive, 0); scenario.wait(15.0); CHECK(locomotive.eimic_real == doctest::Approx(-1.0)); - CHECK(locomotive.Ft == doctest::Approx(0.0)); + CHECK(locomotive.Ft() == doctest::Approx(0.0)); CHECK_FALSE(locomotive.brakes.electrodynamic.on); // coasting: braking with the power of the resistors above, it would lose more than 30 km/h CHECK(locomotive.Vel > speed - 12.0); @@ -114,7 +114,7 @@ TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); CHECK(locomotive.brakes.electrodynamic.on); REQUIRE(locomotive.Vel > 6.0); - CHECK(-locomotive.Ft == doctest::Approx(br285_limit(locomotive)).epsilon(0.01)); + 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.brakes.cylinderPressure < 0.1); @@ -141,16 +141,16 @@ TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { // 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)); + 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); + 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(locomotive.Ft() == doctest::Approx(0.0)); CHECK_FALSE(locomotive.brakes.electrodynamic.on); // it doesn't hold the train: the air brake does CHECK(locomotive.Vel > 0.1); @@ -177,7 +177,7 @@ TEST_CASE("diesel-electric dynamic brake: a resistor brake with its own lever") 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(locomotive.Ft() > 0.0); CHECK_FALSE(locomotive.brakes.electrodynamic.on); scenario.act("power off"); @@ -185,7 +185,7 @@ TEST_CASE("diesel-electric dynamic brake: a resistor brake with its own lever") scenario.wait(4.0); CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); CHECK(locomotive.brakes.electrodynamic.on); - CHECK(-locomotive.Ft == doctest::Approx(st44_limit(locomotive)).epsilon(0.01)); + CHECK(-locomotive.Ft() == doctest::Approx(st44_limit(locomotive)).epsilon(0.01)); CHECK(locomotive.ShowCurrent(0) > 0.0); scenario.act("half the lever"); @@ -197,13 +197,13 @@ TEST_CASE("diesel-electric dynamic brake: a resistor brake with its own lever") 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)); + 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(locomotive.Ft() == doctest::Approx(0.0)); CHECK_FALSE(locomotive.brakes.electrodynamic.on); scenario.check(); } @@ -257,7 +257,7 @@ TEST_CASE("diesel-electric dynamic brake: without a fade it brings the vehicle t 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.Ft() == doctest::Approx(0.0)); } CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); scenario.check(); diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index e754f3d1b..c50bc6eac 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -95,7 +95,7 @@ TEST_CASE("elf controller: without EIMCtrlMainEmergency the positions stay as th REQUIRE(unit.ready); REQUIRE(unit.charged); auto &physics{unit.cab()}; - CHECK_FALSE(physics.EIMCtrlMainEmergency); + CHECK_FALSE(physics.EIMCtrlMainEmergency()); CHECK(physics.EIMCtrlEmergencyPositions() == 0); CHECK(physics.MainCtrlPosNo == 4); CHECK(physics.MainCtrlNoPowerPos() == 3); @@ -113,7 +113,7 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency shifts the positions up by the e REQUIRE(unit.ready); REQUIRE(unit.charged); auto &physics{unit.cab()}; - CHECK(physics.EIMCtrlMainEmergency); + CHECK(physics.EIMCtrlMainEmergency()); CHECK(physics.EIMCtrlEmergencyPositions() == 1); CHECK(physics.MainCtrlPosNo == 5); CHECK(physics.MainCtrlNoPowerPos() == 4); @@ -158,13 +158,13 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency with the old MCPN gets its posit CHECK(car->MainCtrlPosNo == 5); CHECK(car->MainCtrlNoPowerPos() == 4); // DirChangeMaxPos=3 of the file, the old neutral, moves up with the positions - CHECK(car->MainCtrlMaxDirChangePos == 4); + CHECK(car->MainCtrlMaxDirChangePos() == 4); } TEST_CASE("elf controller: EIMCtrlMainEmergency leaves DirChangeMaxPos of the files updated for it alone") { vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "EIMCtrlMainEmergency", "Yes").set("Cntrl", "MCPN", 5).set("Cntrl", "DirChangeMaxPos", 4)}; CHECK(car->MainCtrlPosNo == 5); - CHECK(car->MainCtrlMaxDirChangePos == 4); + CHECK(car->MainCtrlMaxDirChangePos() == 4); } TEST_CASE("elf controller: the reverser works at the neutral shifted by EIMCtrlMainEmergency") { @@ -205,7 +205,7 @@ TEST_CASE("elf controller: an Elf with the emergency brake position leading one REQUIRE(unit.charged); auto &lead{unit.cab()}; auto &other{unit.car(3)}; - REQUIRE_FALSE(other.EIMCtrlMainEmergency); + REQUIRE_FALSE(other.EIMCtrlMainEmergency()); // neutral of the lead is neutral of the other CHECK(lead.MainCtrlPos() == 4); CHECK(other.MainCtrlPos() == other.MainCtrlNoPowerPos()); @@ -235,7 +235,7 @@ TEST_CASE("elf controller: an Elf without the emergency brake position leading o REQUIRE(unit.charged); auto &lead{unit.cab()}; auto &other{unit.car(3)}; - REQUIRE(other.EIMCtrlMainEmergency); + REQUIRE(other.EIMCtrlMainEmergency()); CHECK(lead.MainCtrlPos() == 3); CHECK(other.MainCtrlPos() == other.MainCtrlNoPowerPos()); SUBCASE("power") { @@ -295,15 +295,15 @@ 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; + mass += Unit.car(i).TotalMass(); + axles += Unit.car(i).NAxles(); } auto const force{Unit.cab().brakes.holding.deceleration * mass}; for (std::size_t i = 0; i < Unit.unit.size(); ++i) { auto &car{Unit.car(i)}; auto const nmax{((car.brakes.config.pressureToForce * car.brakes.config.maxCylinderPressure[0] - car.brakes.config.cylinders.springForce) * car.brakes.config.cylinders.leverRatio[0] - car.brakes.config.cylinders.slackAdjusterForce) * car.brakes.config.cylinders.count * car.brakes.config.cylinders.riggingEfficiency}; - auto const fmax{nmax * car.brakes.distributor->GetFC(nmax / (car.NAxles * car.brakes.config.blocksPerAxle), car.brakes.blending.referenceSpeed) * 1000}; - auto position{Hold ? force * car.NAxles / axles / fmax : 0.0}; + auto const fmax{nmax * car.brakes.distributor->GetFC(nmax / (car.NAxles() * car.brakes.config.blocksPerAxle), car.brakes.blending.referenceSpeed) * 1000}; + auto position{Hold ? force * car.NAxles() / axles / fmax : 0.0}; if (position > 0.009) { auto const slack{(car.brakes.config.cylinders.slackAdjusterForce / car.brakes.config.cylinders.leverRatio[0] + car.brakes.config.cylinders.springForce) / (car.brakes.config.pressureToForce * car.brakes.config.maxCylinderPressure[0])}; position = slack + (1 - slack) * position; @@ -521,16 +521,16 @@ TEST_CASE("elf holding brake: the force of the motors at 1% against the holding 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; + 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.brakes.holding.deceleration * mass}; - MESSAGE("mass " << mass << " kg, holding " << holding << " N, cars with motors " << powered << ", demand " << cab.eimic_real << ", cab car Ft " << cab.Ft + MESSAGE("mass " << mass << " kg, holding " << holding << " N, cars with motors " << powered << ", demand " << cab.eimic_real << ", cab car Ft " << cab.Ft() << " N, Fful " << cab.inductionMotor.state.fullForce << " 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); + CHECK(cab.Ft() * powered < 0.1 * holding); } diff --git a/tests/unit/test_engine_start.cpp b/tests/unit/test_engine_start.cpp index b58f0cf77..d8ecfe529 100644 --- a/tests/unit/test_engine_start.cpp +++ b/tests/unit/test_engine_start.cpp @@ -178,7 +178,7 @@ TEST_CASE("engine start: the switch of another vehicle is held for the vehicle's consist train; train.add(sn61(false).set("Cntrl", "IniCDelay", "2.0"), 1); auto &second{train.add(sn61(false).set("Cntrl", "IniCDelay", "2.0")).physics()}; - REQUIRE(second.InitialCtrlDelay == doctest::Approx(2.0)); + REQUIRE(second.InitialCtrlDelay() == doctest::Approx(2.0)); engine_start::remote_switch switchb; // without the battery the switch does nothing, however long it's held diff --git a/tests/unit/test_equipment_faults.cpp b/tests/unit/test_equipment_faults.cpp index bd65cacb4..d87d803a1 100644 --- a/tests/unit/test_equipment_faults.cpp +++ b/tests/unit/test_equipment_faults.cpp @@ -16,18 +16,18 @@ TEST_CASE("equipment faults: the number of a message comes back as it went in") TEST_CASE("equipment faults: the fault of the control opens the line contactors and holds the start until it clears") { test::vehicle loco{test::definition::fiz("4e_v1/4e")}; - auto const delay{loco->InitialCtrlDelay}; + auto const delay{loco->InitialCtrlDelay()}; loco->lineContactors.Close(); loco->SetEquipmentFaults(EquipmentFault::control); CHECK(loco->equipmentFaults.HasAll(EquipmentFault::control)); CHECK_FALSE(loco->lineContactors.IsClosed()); - CHECK(loco->InitialCtrlDelay > 100000000.0); + CHECK(loco->InitialCtrlDelay() > 100000000.0); // set again, it doesn't move the delay further loco->SetEquipmentFaults(EquipmentFault::control); - CHECK(loco->InitialCtrlDelay < 200000000.0); + CHECK(loco->InitialCtrlDelay() < 200000000.0); loco->SetEquipmentFaults({}); CHECK(loco->equipmentFaults.Empty()); - CHECK(loco->InitialCtrlDelay == doctest::Approx(delay)); + CHECK(loco->InitialCtrlDelay() == doctest::Approx(delay)); } TEST_CASE("equipment faults: the fault of the compressor moves its pressures out of reach, and back") { diff --git a/tests/unit/test_field_shunting.cpp b/tests/unit/test_field_shunting.cpp index ac44a4fdc..4c9793294 100644 --- a/tests/unit/test_field_shunting.cpp +++ b/tests/unit/test_field_shunting.cpp @@ -46,10 +46,10 @@ TEST_CASE("field shunting: the SU45 with its switch, off at full power and switc scenario.add("bdhpumn_v3/bdhpumn"); REQUIRE(scenario.start_up()); auto &su45{scenario.driver().controlling}; - REQUIRE(su45.AutoRelayType == 2); - REQUIRE(su45.FieldShuntSwitch); + REQUIRE(su45.AutoRelayType() == 2); + REQUIRE(su45.FieldShuntSwitch()); // the driver switches it on as the AI does, getting the locomotive ready - CHECK(su45.AutoRelayFlag); + CHECK(su45.AutoRelayFlag()); scenario.act("field shunting off"); CHECK(su45.AutoRelaySwitch(false)); scenario.get_going(); @@ -65,7 +65,7 @@ TEST_CASE("field shunting: the SU45 with its switch, off at full power and switc scenario.act("field shunting on"); CHECK(su45.AutoRelaySwitch(true)); scenario.wait(30.0); - CHECK(su45.ScndCtrlPos() == su45.ScndCtrlPosNo); + CHECK(su45.ScndCtrlPos() == su45.ScndCtrlPosNo()); scenario.act("field shunting off on the move"); CHECK(su45.AutoRelaySwitch(false)); scenario.wait(1.0); @@ -81,9 +81,9 @@ TEST_CASE("field shunting: a diesel-electric with AutoRelay=Optional alone shunt 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); + REQUIRE(su45.AutoRelayType() == 2); + REQUIRE_FALSE(su45.FieldShuntSwitch()); + CHECK_FALSE(su45.AutoRelayFlag()); scenario.get_going(); scenario.full_power(120.0); CHECK(su45.IsMainCtrlMaxPowerPos()); diff --git a/tests/unit/test_fiz.cpp b/tests/unit/test_fiz.cpp index 31087a141..51488f5de 100644 --- a/tests/unit/test_fiz.cpp +++ b/tests/unit/test_fiz.cpp @@ -26,11 +26,11 @@ TEST_CASE("fiz: every real vehicle loads and keeps its parameters") { trace.sample(0.0, real.physics()); // what every vehicle has, the rest of its parameters are in the golden trace CHECK(real->Mass > 0.0); - CHECK(real->TotalMass >= real->Mass); - CHECK(real->Vmax > 0.0); - CHECK(real->NAxles > 0); - CHECK(real->WheelDiameter > 0.0); - CHECK(real->NPoweredAxles <= real->NAxles); + CHECK(real->TotalMass() >= real->Mass); + CHECK(real->Vmax() > 0.0); + CHECK(real->NAxles() > 0); + CHECK(real->WheelDiameter() > 0.0); + CHECK(real->NPoweredAxles() <= real->NAxles()); trace.check(); } } @@ -42,7 +42,7 @@ TEST_CASE("fiz: changes made by a test reach the vehicle") { // a key the file doesn't have is added to its section CHECK(vehicle{definition{eu07}.set("Brake", "MaxBP", 3.5)}->brakes.config.maxCylinderPressure[3] == doctest::Approx(3.5)); // removing a key brings its default back - CHECK(vehicle{definition{eu07}.remove("Param", "Vmax")}->Vmax != doctest::Approx(125.0)); + CHECK(vehicle{definition{eu07}.remove("Param", "Vmax")}->Vmax() != doctest::Approx(125.0)); } namespace { diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index 36943bf84..b26654f8d 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -111,7 +111,7 @@ void notch_up(physics::Vehicle &Cab) { // the power at the wheels [kW] double wheel_power(physics::Vehicle const &Vehicle) { - return std::abs(Vehicle.Ft * Vehicle.V()) / 1000.0; + return std::abs(Vehicle.Ft() * Vehicle.V()) / 1000.0; } // one step of 0.01 s, acknowledging the vigilance once a second @@ -341,7 +341,7 @@ TEST_CASE("genset: running from the catenary is the same with the keys") { }; auto const record = [](values &Values) { return std::vector{ - {"Ft", [&Values](physics::Vehicle const &Vehicle) { Values.force.push_back(Vehicle.Ft); return Vehicle.Ft; }}, + {"Ft", [&Values](physics::Vehicle const &Vehicle) { Values.force.push_back(Vehicle.Ft()); return Vehicle.Ft(); }}, {"V", [&Values](physics::Vehicle const &Vehicle) { Values.speed.push_back(Vehicle.V()); return Vehicle.V(); }}, {"EngineVoltage", [&Values](physics::Vehicle const &Vehicle) { Values.voltage.push_back(Vehicle.EngineVoltage); return Vehicle.EngineVoltage; }}, {"Itot", [&Values](physics::Vehicle const &Vehicle) { Values.current.push_back(Vehicle.Itot); return Vehicle.Itot; }}, diff --git a/tests/unit/test_handover.cpp b/tests/unit/test_handover.cpp index dd5ed15ae..ec43a2b3a 100644 --- a/tests/unit/test_handover.cpp +++ b/tests/unit/test_handover.cpp @@ -38,11 +38,11 @@ TEST_CASE("handover: the horn the AI was sounding goes quiet (eu07/maszyna#511)" TEST_CASE("handover: sanding the AI started stops") { auto cab{cab_vehicle()}; cab->Sandbox(true); // the way the AI sands, bypassing the sanding button - REQUIRE(cab->SandDose); + REQUIRE(cab->SandDose()); handover::release_ai_controls(cab.physics(), cab.physics()); - CHECK_FALSE(cab->SandDose); + CHECK_FALSE(cab->SandDose()); } TEST_CASE("handover: sanding the player or the automatic system asked for goes on") { @@ -52,11 +52,11 @@ TEST_CASE("handover: sanding the player or the automatic system asked for goes o cab->SandboxAutoAllow(true); cab->SandboxAuto(true); } - REQUIRE(cab->SandDose); + REQUIRE(cab->SandDose()); handover::release_ai_controls(cab.physics(), cab.physics()); - CHECK(cab->SandDose); + CHECK(cab->SandDose()); } TEST_CASE("handover: the departure signal the AI was giving stops") { @@ -85,7 +85,7 @@ TEST_CASE("handover: nothing the AI didn't latch changes") { handover::release_ai_controls(cab.physics(), cab.physics()); CHECK(cab->WarningSignal() == 0); - CHECK_FALSE(cab->SandDose); + CHECK_FALSE(cab->SandDose()); CHECK_FALSE(cab->DepartureSignal); CHECK_FALSE(cab->brakes.distributor->Releaser()); } @@ -136,7 +136,7 @@ TEST_CASE("handover: the light selector already matching the lights stays") { TEST_CASE("handover: the headlight dimmer leaves the off position when the head lights are lit") { auto cab{cab_vehicle()}; - REQUIRE(cab->enableModernDimmer); + REQUIRE(cab->enableModernDimmer()); REQUIRE(cab->dimPositions.size() == 5); cab->SetDimmerPosition(2); // off, left there by the player before the AI took over @@ -163,7 +163,7 @@ TEST_CASE("handover: the headlight dimmer in any other position stays") { TEST_CASE("handover: a vehicle without the modern dimmer keeps its dimmer state") { vehicle wagon{definition::load("wagon")}; - REQUIRE_FALSE(wagon->enableModernDimmer); + REQUIRE_FALSE(wagon->enableModernDimmer()); CHECK(handover::dimmer_position(wagon.physics(), true) == wagon->DimmerPosition()); } diff --git a/tests/unit/test_horn.cpp b/tests/unit/test_horn.cpp index 65c600944..4c9fd7fb3 100644 --- a/tests/unit/test_horn.cpp +++ b/tests/unit/test_horn.cpp @@ -55,7 +55,7 @@ int const allhorns{horn::low | horn::high | 4}; TEST_CASE("horn: a pneumatic horn sounds on the air of the main reservoir only") { auto vehicle{horn_vehicle(test::definition::load("wagon"))}; - REQUIRE(vehicle->HornSupply == horn_supply::air); // the default + REQUIRE(vehicle->HornSupply() == horn_supply::air); // the default vehicle->air.SetPressureForTest(6.5); CHECK(vehicle->SoundingHorns(allhorns) == allhorns); @@ -75,7 +75,7 @@ TEST_CASE("horn: a vehicle without a main reservoir takes the horn air from the TEST_CASE("horn: an electric horn sounds on the low voltage, whatever the air") { auto vehicle{horn_vehicle(test::definition::load("wagon").set("Cntrl", "HornType", "Electric"))}; - REQUIRE(vehicle->HornSupply == horn_supply::electric); + REQUIRE(vehicle->HornSupply() == horn_supply::electric); REQUIRE(vehicle->Horn3Supply == horn_supply::electric); // the third horn follows the others unless told otherwise vehicle->air.SetPressureForTest(0.0); @@ -87,7 +87,7 @@ TEST_CASE("horn: an electric horn sounds on the low voltage, whatever the air") TEST_CASE("horn: the third horn can have a supply of its own, an electric horn of a diesel say") { auto vehicle{horn_vehicle(test::definition::load("wagon").set("Cntrl", "Horn3Type", "Electric"))}; - REQUIRE(vehicle->HornSupply == horn_supply::air); + REQUIRE(vehicle->HornSupply() == horn_supply::air); REQUIRE(vehicle->Horn3Supply == horn_supply::electric); vehicle->air.SetPressureForTest(0.0); diff --git a/tests/unit/test_loads.cpp b/tests/unit/test_loads.cpp index 123389155..ee35a6e2a 100644 --- a/tests/unit/test_loads.cpp +++ b/tests/unit/test_loads.cpp @@ -35,11 +35,11 @@ TEST_CASE("loads: the pantographs of an electric vehicle set up by the amount of TEST_CASE("loads: a load assigned, of one kind at a time, up to the vehicle's capacity, and emptied") { vehicle wagon{definition::fiz("3wl_v2/3wl")}; - auto const empty{wagon->TotalMass}; + auto const empty{wagon->TotalMass()}; REQUIRE(wagon->AssignLoad("coal", 10.f)); CHECK(wagon->LoadTypeChange()); CHECK(wagon->LoadType.name == "coal"); - CHECK(wagon->TotalMass > empty); + CHECK(wagon->TotalMass() > empty); // more of the same: the amount set, not added, and no more than the vehicle takes wagon->TakeLoadTypeChange(); REQUIRE(wagon->AssignLoad("coal", 1000.f)); diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp index f4aacbfc2..3c8748795 100644 --- a/tests/unit/test_pullee.cpp +++ b/tests/unit/test_pullee.cpp @@ -76,7 +76,7 @@ TEST_CASE("pullee: a dead Vectron vents the brake pipe of the train hauling it, SUBCASE("as it is") { hauled_train train{vectron, 60.0, false}; REQUIRE((train.hauled->InactiveCabFlag & activation::emergencybrake) != 0); - REQUIRE_FALSE(train.hauled->PulleeMode); + REQUIRE_FALSE(train.hauled->PulleeMode()); train.run(120.0); CHECK(train.hauled->brakes.emergencyValve.flow > 0.0); CHECK(train.locomotive->brakePipe.Pressure() < 4.95); // the pipe sags although the locomotive keeps feeding it @@ -320,9 +320,9 @@ TEST_CASE("pullee: entering the mode lets go of the hand brake and the spring br SUBCASE("a locomotive standing braked, its spring brake switched on") { vehicle vectron{definition::fiz("vectron_v1/wariant_7w")}; REQUIRE(vectron->brakes.spring.activate); - REQUIRE_FALSE(vectron->PulleeMode); + REQUIRE_FALSE(vectron->PulleeMode()); CHECK(vectron->PulleeModeSwitch(true)); - CHECK(vectron->PulleeMode); + CHECK(vectron->PulleeMode()); CHECK_FALSE(vectron->brakes.spring.activate); // already in it CHECK_FALSE(vectron->PulleeModeSwitch(true)); @@ -355,14 +355,14 @@ TEST_CASE("pullee: the battery and the cabs of a vehicle prepared for hauling st CHECK(vectron->brakes.emergencyValve.flow == 0.0); REQUIRE(vectron->PulleeModeSwitch(false)); - CHECK_FALSE(vectron->PulleeMode); + CHECK_FALSE(vectron->PulleeMode()); CHECK(vectron->BatterySwitch(true)); CHECK(vectron->lowVoltage.IsBatteryOn()); 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); + CHECK_FALSE(vectron->PulleeMode()); } TEST_CASE("pullee: a cab activated on a dead battery calls the emergency brake, which the mode keeps from happening") { diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp index 9ce81b736..516334cbf 100644 --- a/tests/unit/test_speed_control.cpp +++ b/tests/unit/test_speed_control.cpp @@ -21,7 +21,7 @@ std::vector cruise() { {"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; }}, + {"eimicSpeedCtrl", [](auto const &M) { return M.eimicSpeedCtrl(); }}, {"eimic_real", [](auto const &M) { return M.eimic_real; }}, }; } @@ -73,8 +73,8 @@ TEST_CASE("speed control: the field shunting of the vehicles without a cruise co 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_FALSE(loco.SpeedCtrl()); + REQUIRE_FALSE(loco.AutoRelayFlag()); REQUIRE(scenario.start_up()); scenario.get_going(); scenario.full_power(60.0); @@ -99,8 +99,8 @@ TEST_CASE("speed control: the field shunting of the vehicles without a cruise co 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_FALSE(loco.SpeedCtrl()); + REQUIRE(loco.AutoRelayFlag()); REQUIRE(scenario.start_up()); scenario.get_going(); scenario.full_power(5.0); @@ -109,7 +109,7 @@ TEST_CASE("speed control: the field shunting of the vehicles without a cruise co scenario.wait(10.0); most = std::max(most, loco.ScndCtrlPos()); } - CHECK(most == loco.ScndCtrlPosNo); + CHECK(most == loco.ScndCtrlPosNo()); // the driver can't move it CHECK_FALSE(loco.DecScndCtrl(2)); CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); @@ -126,8 +126,8 @@ TEST_CASE("speed control: the vehicles whose secondary controller is the cruise 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(unit.SpeedCtrl()); + REQUIRE(unit.ScndCtrlPosNo() == 1); REQUIRE(scenario.start_up()); scenario.get_going(); scenario.full_power(40.0); @@ -151,9 +151,9 @@ TEST_CASE("speed control: the vehicles whose secondary controller is the cruise 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(loco.SpeedCtrl()); + REQUIRE(loco.SpeedCtrlTypeTime()); + REQUIRE(loco.ScndCtrlPosNo() == 4); REQUIRE(scenario.start_up()); scenario.get_going(); scenario.act("raise"); @@ -162,11 +162,11 @@ TEST_CASE("speed control: the vehicles whose secondary controller is the cruise } REQUIRE(loco.ScndCtrlPos() == 3); scenario.wait(10.0); - CHECK(loco.NewSpeed > 0.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.SpeedCtrlValue == doctest::Approx(loco.NewSpeed())); CHECK(loco.SpeedCtrlUnit.IsActive); scenario.full_power(60.0); CHECK(loco.Vel == doctest::Approx(loco.SpeedCtrlValue).epsilon(0.1)); @@ -185,9 +185,9 @@ TEST_CASE("speed control: the field shunting of the vehicles with a cruise contr 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); + REQUIRE(loco.SpeedCtrl()); + REQUIRE(loco.AutoRelayFlag()); + REQUIRE(loco.ScndCtrlPosNo() == 1); get_6dg_going(scenario); scenario.act("raise"); move_to(loco, dg_raise); @@ -209,8 +209,8 @@ TEST_CASE("speed control: the field shunting of the vehicles with a cruise contr 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(loco.SpeedCtrl()); + REQUIRE(loco.AutoRelayFlag()); REQUIRE(scenario.start_up()); scenario.get_going(); scenario.full_power(5.0); diff --git a/tests/unit/test_traction.cpp b/tests/unit/test_traction.cpp index 2073fae32..15b00e0fe 100644 --- a/tests/unit/test_traction.cpp +++ b/tests/unit/test_traction.cpp @@ -104,7 +104,7 @@ TEST_CASE("traction: the ET42 at the high current setting, its halves in series, CHECK(et42.CurrentSwitch(high) == high); // the relay takes the setting at the next step, with the controller at zero scenario.get_going(); - CHECK((et42.Imax == et42.ImaxHi) == high); + CHECK((et42.Imax == et42.ImaxHi()) == high); scenario.full_power(60.0); // at the high current setting the controller stops at the last series position: the halves' motors stay // in series, at half the voltage each, for a heavy start, and the train crawls @@ -154,7 +154,7 @@ TEST_CASE("traction: the field shunting relays of the diesel-electric locomotive CHECK(controlling.RelayType == relaytype); scenario.get_going(); scenario.full_power(120.0); - CHECK(controlling.ScndCtrlPos() == controlling.ScndCtrlPosNo); + CHECK(controlling.ScndCtrlPos() == controlling.ScndCtrlPosNo()); auto expected{shunting.begin()}; for (auto const position : {11, 10, 7, 3}) { CAPTURE(position); @@ -201,8 +201,8 @@ TEST_CASE("traction: the induction motor drive's speed control, its electrodynam scenario.get_going(); // the second controller of the EU47 sets the speed to hold (SpeedCtrlType=Time): position 2 keeps the speed // set, 3 raises it by 10 km/h every SpeedCtrlDelay, 4 sets the top speed, 1 lowers it, 0 drops it - REQUIRE(eu47.ScndCtrlPosNo == 4); - REQUIRE(eu47.SpeedCtrlTypeTime); + REQUIRE(eu47.ScndCtrlPosNo() == 4); + REQUIRE(eu47.SpeedCtrlTypeTime()); scenario.full_power(0.0); scenario.act("speed up"); for (int i = 0; i < 3; ++i) { @@ -227,7 +227,7 @@ TEST_CASE("traction: the induction motor drive's speed control, its electrodynam scenario.act("top speed"); eu47.IncScndCtrl(2); scenario.wait(5.0); - CHECK(eu47.SpeedCtrlValue == doctest::Approx(eu47.Vmax)); + CHECK(eu47.SpeedCtrlValue == doctest::Approx(eu47.Vmax())); scenario.act("speed control off"); while (eu47.DecScndCtrl(1)) { // down to zero diff --git a/tests/unit/test_uc_steps.cpp b/tests/unit/test_uc_steps.cpp index a25397b23..889774d48 100644 --- a/tests/unit/test_uc_steps.cpp +++ b/tests/unit/test_uc_steps.cpp @@ -56,7 +56,7 @@ bool on_step(double const Value, double const Step) { TEST_CASE("controls: the universal controller with CtrlValStep sets its power in whole steps") { test::track const line{0.15, 0.0}; vehicle railbus{definition::fiz("21xm_v1/214ma").set("UCList", "CtrlValStep", 0.05), 0.0, "test", 1}; - REQUIRE(railbus->UniCtrlValStep == doctest::Approx(0.05)); + REQUIRE(railbus->UniCtrlValStep() == doctest::Approx(0.05)); get_ready(railbus, line); // a tap on the raising position: one step at once, kept by the holding one @@ -104,7 +104,7 @@ TEST_CASE("controls: the universal controller with CtrlValStep sets its power in TEST_CASE("controls: the universal controller without CtrlValStep sets its power continuously, as before") { test::track const line{0.15, 0.0}; vehicle railbus{definition::fiz("21xm_v1/214ma"), 0.0, "test", 1}; - REQUIRE(railbus->UniCtrlValStep == 0.0); + REQUIRE(railbus->UniCtrlValStep() == 0.0); get_ready(railbus, line); // a tap moves it by 0.01, held it goes on at 0.15 a second after the initial delay move_to(railbus, raise); diff --git a/tests/unit/test_wheelslip.cpp b/tests/unit/test_wheelslip.cpp index 842eb31e2..934f40f05 100644 --- a/tests/unit/test_wheelslip.cpp +++ b/tests/unit/test_wheelslip.cpp @@ -22,7 +22,7 @@ braking_result brake_to_stop_then_stand(vehicle &Coach, track const &Braking, tr Coach.hold_brake_pipe(3.5); // service braking // a skidding wagon brakes on the sliding adhesion only, give it time for (auto step = 0; step < 60000; ++step) { // 600 s in 0.01 s steps - result.skidded |= Coach->SlippingWheels; + result.skidded |= Coach->SlippingWheels(); if (auto const speed{std::abs(Coach.speed())}; speed > 0.0 && speed < 0.1) { // almost stopped; a skidding wagon is still skidding at this point result.stopped = true; @@ -58,5 +58,5 @@ TEST_CASE("wheelslip: a wagon which stopped in a skid holds like one which stopp CHECK(std::abs(normal.speed()) < 0.1); CHECK(std::abs(skidding.speed()) < 0.1); - CHECK_FALSE(skidding->SlippingWheels); + CHECK_FALSE(skidding->SlippingWheels()); } diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index e508025d4..796005ddd 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -142,7 +142,7 @@ vehicle::vehicle(definition const &Definition, double Velocity, std::string cons // a driver keeps a vehicle on standby on its independent brake if (Cab != 0 && m_physics->brakes.config.localKind != TLocalBrake::ManualBrake && Velocity < 1.0) { m_physics->IncLocalBrakeLevel(LocalBrakePosNo); - if (m_physics->EIMCtrlEmergency) { + if (m_physics->EIMCtrlEmergency()) { m_physics->DecLocalBrakeLevel(1); } } @@ -240,16 +240,16 @@ double vehicle::move(track const &Track, double Dt, TLocation const &Location, d physics.brakes.equivalentPipePressure = Trainpipe; if (auto const diesel{physics.EngineType == DieselEngine || physics.EngineType == DieselElectric}; diesel && physics.EIMCtrlType > 0) { physics.CheckEIMIC(Dt); - if (physics.SpeedCtrl) { + if (physics.SpeedCtrl()) { physics.CheckSpeedCtrl(Dt); } - physics.eimic_real = std::min(physics.eimic, physics.eimicSpeedCtrl); + physics.eimic_real = std::min(physics.eimic, physics.eimicSpeedCtrl()); } if (physics.EngineType == ElectricInductionMotor) { // the share of the electric and pneumatic brake over the train (TDynamicObject's MED) isn't here physics.CheckEIMIC(Dt); physics.CheckSpeedCtrl(Dt); - physics.eimic_real = std::min(physics.eimic, physics.eimicSpeedCtrl); + physics.eimic_real = std::min(physics.eimic, physics.eimicSpeedCtrl()); } } diff --git a/utilities/motiontelemetry.cpp b/utilities/motiontelemetry.cpp index 8703cb41f..c263c23ea 100644 --- a/utilities/motiontelemetry.cpp +++ b/utilities/motiontelemetry.cpp @@ -100,7 +100,7 @@ void motiontelemetry::update() if (conf.fwdposbased) local_acc.z += glm::dot(acc, frontvector); else - local_acc.z += t->Occupied()->AccSVBased; + local_acc.z += t->Occupied()->AccSVBased(); local_acc /= 9.81; diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index 1de5dc1af..b982edce5 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -208,7 +208,7 @@ void TController::AutoRewident() if( OrderCurrentGet() & ( DriverOrder::obeyTrain | DriverOrder::bank ) ) { // 4. Przeliczanie siły hamowania - double const velstep = occupied->Vmax * 0.5 / BrakeAccTableSize; + double const velstep = occupied->Vmax() * 0.5 / BrakeAccTableSize; auto *d = pVehicles[0]; // pojazd na czele składu while (d) { // a vehicle with its brake cut out (by the inspector above or for a reason of its own) adds its mass only; @@ -334,8 +334,8 @@ bool TController::CheckVehicles(DriverOrders user) ++iVehicles; // jest jeden pojazd więcej pVehicles[VehicleEnd::rear] = p; // zapamiętanie ostatniego fLength += p->physics->Dim.L; // dodanie długości pojazdu - fMass += p->physics->TotalMass; // dodanie masy łącznie z ładunkiem - fVelMax = min_speed( fVelMax, p->physics->Vmax ); // ustalenie maksymalnej prędkości dla składu + fMass += p->physics->TotalMass(); // dodanie masy łącznie z ładunkiem + fVelMax = min_speed( fVelMax, p->physics->Vmax() ); // ustalenie maksymalnej prędkości dla składu // reset oerlikon brakes consist flag as different type was detected if( p->physics->brakes.config.subsystem != TBrakeSubSystem::ss_ESt && p->physics->brakes.config.subsystem != TBrakeSubSystem::ss_LSt ) { @@ -556,7 +556,7 @@ void TController::DirectionForward(bool forward) { // ustawienie jazdy do przodu dla true i do tyłu dla false (zależy od kabiny) ZeroSpeed( true ); // TODO: check if force switch is needed anymore here // HACK: make sure the master controller isn't set in position which prevents direction change - mvControlling->SetMainCtrlPos(std::min( mvControlling->MainCtrlPos(), mvControlling->MainCtrlMaxDirChangePos )); + mvControlling->SetMainCtrlPos(std::min( mvControlling->MainCtrlPos(), mvControlling->MainCtrlMaxDirChangePos() )); if( forward ) { // do przodu w obecnej kabinie @@ -574,7 +574,7 @@ void TController::DirectionForward(bool forward) iTableDirection = 0; } } - if( occupied->TrainType == train_type::sn61 ) { + if( occupied->TrainType() == train_type::sn61 ) { // specjalnie dla SN61 żeby nie zgasł while( mvControlling->RList[mvControlling->MainCtrlPos()].Mn == 0 && mvControlling->IncMainCtrl(1) ) { @@ -593,7 +593,7 @@ void TController::sync_consist_reversers() { auto const currentdirection { occupied->DirActive }; auto const fastforward { is_emu() && occupied->EngineType != TEngineType::ElectricInductionMotor - && occupied->Imin == occupied->IminHi }; + && occupied->Imin() == occupied->IminHi }; // move reverser all way in the opposite direction... for( auto idx = 0; idx < 3; ++idx ) { @@ -677,12 +677,12 @@ TController::determine_consist_state() { cue_action( driver_hint::cabactivation ); } else if (!occupied->AutomaticCabActivation - && ( occupied->CabActive == -occupied->CabOccupied() || !occupied->CabMaster || !occupied->lowVoltage.Is24vAvailable() ) ) + && ( occupied->CabActive == -occupied->CabOccupied() || !occupied->CabMaster() || !occupied->lowVoltage.Is24vAvailable() ) ) { cue_action( driver_hint::cabdeactivation ); } - int index = double(BrakeAccTableSize) * (occupied->Vel / occupied->Vmax); + int index = double(BrakeAccTableSize) * (occupied->Vel / occupied->Vmax()); index = std::min(BrakeAccTableSize, std::max(1, index)); fBrake_a0[0] = fBrake_a0[index]; fBrake_a1[0] = fBrake_a1[index]; @@ -716,7 +716,7 @@ TController::determine_consist_state() { { // sprawdzenie odhamowania wszystkich połączonych pojazdów auto *vehicle { p->physics }; auto const bp { std::max( 0.0, vehicle->brakes.cylinderPressure - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->brakes.config.maxCylinderPressure[ 0 ] * vehicle->brakes.holding.deceleration : 0.0 ) ) }; - momentum += vehicle->TotalMass * vehicle->V() * ( p->DirectionGet() == iDirection ? 1 : -1 ); + momentum += vehicle->TotalMass() * vehicle->V() * ( p->DirectionGet() == iDirection ? 1 : -1 ); mostapplied = std::max( bp, mostapplied ); if( ( vehicle->brakes.config.kind != TBrakeSystem::Individual ) && ( vehicle->brakes.config.maxCylinderPressure[ 3 ] > 0.0 ) @@ -836,7 +836,7 @@ TController::determine_consist_state() { absaccs = 0; auto *d = pVehicles[ VehicleEnd::front ]; // pojazd na czele składu while( d ) { - absaccs += d->physics->TotalMass * d->physics->AccS() * ( d->DirectionGet() == iDirection ? 1 : -1 ); + absaccs += d->physics->TotalMass() * d->physics->AccS() * ( d->DirectionGet() == iDirection ? 1 : -1 ); d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) } absaccs *= iDirection >= 0 ? 1 : -1; diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index e8cacff77..c996d3846 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -60,7 +60,7 @@ TController::increase_train_brake() { while (d) { // przeliczanie dodatkowego potrzebnego spadku ciśnienia if( ( d->physics->brakes.distributor->GetBrakeStatus() & b_dmg ) == 0 ) { - pos_corr -= ( std::min( 5.0, d->physics->brakes.distributor->GetCRP() ) - 5.0 ) * d->physics->TotalMass; + pos_corr -= ( std::min( 5.0, d->physics->brakes.distributor->GetCRP() ) - 5.0 ) * d->physics->TotalMass(); } d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) } @@ -143,8 +143,8 @@ bool TController::IncBrake() } // NOTE: can't perform just test whether connected vehicle == nullptr, due to virtual couplers formed with nearby vehicles auto standalone { true }; - if( occupied->TrainType == train_type::et41 - || occupied->TrainType == train_type::et42 ) { + if( occupied->TrainType() == train_type::et41 + || occupied->TrainType() == train_type::et42 ) { // NOTE: we're doing simplified checks full of presuptions here. // they'll break if someone does strange thing like turning around the second unit if( occupied->Couplers[VehicleEnd::rear].CouplingFlag & Coupling::permanent @@ -236,7 +236,7 @@ bool TController::IncBrake() std::lerp( occupied->brakes.driverValve->GetPos( bh_EPR ), occupied->brakes.driverValve->GetPos( bh_EPB ), - std::clamp( -AccDesired / AccMax * occupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); + std::clamp( -AccDesired / AccMax * occupied->AIHintLocalBrakeAccFactor(), 0.0, 1.0 ) ) ); OK = occupied->brakes.HandlePositionSmooth() != initialbrakeposition; } else if( occupied->brakes.HandlePositionSmooth() != occupied->brakes.driverValve->GetPos( bh_EPB ) ) { @@ -269,9 +269,9 @@ bool TController::IncBrakeEIM() { case 0: { if( occupied->brakes.blending.maxDeceleration != 9.81 ) { - auto const maxpos{occupied->EIMCtrlEmergency ? 0.9 : 1.0 }; + auto const maxpos{occupied->EIMCtrlEmergency() ? 0.9 : 1.0 }; auto const brakelimit{ -2.2 * AccDesired / fMedAmax - 1.0}; //additional limit when hinted is too low - auto const brakehinted{ -1.0 * occupied->AIHintLocalBrakeAccFactor * AccDesired / fMedAmax }; //preffered by AI + auto const brakehinted{ -1.0 * occupied->AIHintLocalBrakeAccFactor() * AccDesired / fMedAmax }; //preffered by AI auto const brakeposition{ maxpos * std::clamp(std::max(brakelimit, brakehinted), 0.0, 1.0)}; OK = brakeposition != occupied->brakes.IndependentPosition(); occupied->brakes.SetIndependentPosition(brakeposition); @@ -296,7 +296,7 @@ bool TController::IncBrakeEIM() break; } case 3: { - if( occupied->UniCtrlIntegratedLocalBrakeCtrl ) { + if( occupied->UniCtrlIntegratedLocalBrakeCtrl() ) { OK = occupied->MainCtrlPos() > 0; if( OK ) occupied->SetMainCtrlPos(0); @@ -398,7 +398,7 @@ bool TController::DecBrake() { std::lerp( occupied->brakes.driverValve->GetPos( bh_EPR ), occupied->brakes.driverValve->GetPos( bh_EPB ), - std::clamp( -AccDesired / AccMax * occupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); + std::clamp( -AccDesired / AccMax * occupied->AIHintLocalBrakeAccFactor(), 0.0, 1.0 ) ) ); OK = occupied->brakes.HandlePositionSmooth() != initialbrakeposition; } else { @@ -437,7 +437,7 @@ void TController::LapBrake() { void TController::ZeroLocalBrake() { - if( occupied->UniCtrlIntegratedLocalBrakeCtrl ) { + if( occupied->UniCtrlIntegratedLocalBrakeCtrl() ) { while( DecBrakeEIM() ) { ; } @@ -455,7 +455,7 @@ bool TController::DecBrakeEIM() case 0: { if( occupied->brakes.blending.maxDeceleration != 9.81 ) { auto const desiredacceleration { ( occupied->Vel > EU07_AI_NOMOVEMENT ? AccDesired : std::max( 0.0, AccDesired ) ) }; - auto const brakeposition { std::clamp( -1.0 * occupied->AIHintLocalBrakeAccFactor * desiredacceleration / occupied->brakes.blending.maxDeceleration, 0.0, 1.0 ) }; + auto const brakeposition { std::clamp( -1.0 * occupied->AIHintLocalBrakeAccFactor() * desiredacceleration / occupied->brakes.blending.maxDeceleration, 0.0, 1.0 ) }; OK = brakeposition != occupied->brakes.IndependentPosition(); occupied->brakes.SetIndependentPosition(brakeposition); } @@ -478,9 +478,9 @@ bool TController::DecBrakeEIM() break; } case 3: { - OK = occupied->MainCtrlPos() < occupied->MainCtrlMaxDirChangePos; + OK = occupied->MainCtrlPos() < occupied->MainCtrlMaxDirChangePos(); if( OK ) - occupied->SetMainCtrlPos(occupied->MainCtrlMaxDirChangePos); + occupied->SetMainCtrlPos(occupied->MainCtrlMaxDirChangePos()); break; } } @@ -511,8 +511,8 @@ bool TController::IncSpeed() if (!IsAnyMotorOverloadRelayOpen && !mvControlling->protection.PressureSwitchTripped() && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->lineContactors.IsClosed()) && (Ready || drivingFlags.press)) { // youBy polecił dodać 2012-09-08 v367 // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) - auto const usehighoverloadrelaythreshold{mvControlling->TrainType != train_type::et42 // ET42 uses these variables for different purpose. TODO: fix this - && mvControlling->ImaxHi > mvControlling->ImaxLo && occupied->Vel < (mvControlling->IsMotorOverloadRelayHighThresholdOn() ? 30.0 : 20.0) && + auto const usehighoverloadrelaythreshold{mvControlling->TrainType() != train_type::et42 // ET42 uses these variables for different purpose. TODO: fix this + && mvControlling->ImaxHi() > mvControlling->ImaxLo() && occupied->Vel < (mvControlling->IsMotorOverloadRelayHighThresholdOn() ? 30.0 : 20.0) && iVehicles - ControlledEnginesCount > 0 // && ( std::fabs( mvControlling->Im ) > 0.85 * mvControlling->Imax ) && mvControlling->Imax * mvControlling->EngineVoltage * ControlledEnginesCount / @@ -524,14 +524,14 @@ bool TController::IncSpeed() // if the power station is heavily burdened, // if it generates enough traction force // to build up speed to 30/40 km/h for passenger/cargo train (10 km/h less if going uphill) - auto const sufficienttractionforce{std::abs(mvControlling->Ft) * ControlledEnginesCount > (IsHeavyCargoTrain ? 75 : 50) * 1000.0}; + auto const sufficienttractionforce{std::abs(mvControlling->Ft()) * ControlledEnginesCount > (IsHeavyCargoTrain ? 75 : 50) * 1000.0}; auto const sufficientacceleration{AbsAccS >= (IsHeavyCargoTrain ? 0.03 : IsCargoTrain ? 0.06 : 0.09)}; auto const seriesmodefieldshunting{mvControlling->ScndCtrlPos() > 0 && mvControlling->RList[mvControlling->MainCtrlPos()].Bn == 1}; auto const parallelmodefieldshunting{mvControlling->ScndCtrlPos() > 0 && mvControlling->RList[mvControlling->MainCtrlPos()].Bn > 1}; auto const minvoltage{(pantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? pantographUnit->EnginePowerSource.CollectorParameters.MinV : 0.0)}; auto const maxvoltage{(pantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? pantographUnit->EnginePowerSource.CollectorParameters.MaxV : 0.0)}; auto const seriesmodevoltage{std::lerp(minvoltage, maxvoltage, IsHeavyCargoTrain ? 0.35 : 0.40)}; - auto const useseriesmode = mvControlling->Imax > mvControlling->ImaxLo || true == usehighoverloadrelaythreshold || fVoltage < seriesmodevoltage || + auto const useseriesmode = mvControlling->Imax > mvControlling->ImaxLo() || true == usehighoverloadrelaythreshold || fVoltage < seriesmodevoltage || (true == sufficientacceleration && true == sufficienttractionforce && occupied->Vel <= (IsCargoTrain ? 40 : 30) + (seriesmodefieldshunting ? 5 : 0) - (fAccGravity < -0.025 ? 10 : 0)); // when not in series mode use the first available parallel mode configuration until 50/60 km/h for passenger/cargo train @@ -543,11 +543,11 @@ bool TController::IncSpeed() mvControlling->MainCtrlPos() == mvControlling->MainCtrlPosNo); // if needed enable high threshold for overload relay... - if (mvControlling->TrainType != train_type::et42) + if (mvControlling->TrainType() != train_type::et42) { // ET42 uses these variables for different purpose. TODO: fix this if (usehighoverloadrelaythreshold) { - if (mvControlling->Imax < mvControlling->ImaxHi) + if (mvControlling->Imax < mvControlling->ImaxHi()) { // to enable this setting we'll typically need the main controller in series mode (which is not guaranteed) if (mvControlling->RList[mvControlling->MainCtrlPos()].Bn > 1) @@ -567,7 +567,7 @@ bool TController::IncSpeed() // ...or disable high threshold for overload relay if no longer needed else { - if (mvControlling->IsMotorOverloadRelayHighThresholdOn() && std::fabs(mvControlling->Im) < mvControlling->ImaxLo) + if (mvControlling->IsMotorOverloadRelayHighThresholdOn() && std::fabs(mvControlling->Im) < mvControlling->ImaxLo()) { mvControlling->CurrentSwitch(false); // rozruch wysoki wyłącz } @@ -575,12 +575,12 @@ bool TController::IncSpeed() } double Vs = 99999; - if (usefieldshunting ? mvControlling->ScndCtrlPos() < mvControlling->ScndCtrlPosNo : mvControlling->MainCtrlPos() < mvControlling->MainCtrlPosNo) + if (usefieldshunting ? mvControlling->ScndCtrlPos() < mvControlling->ScndCtrlPosNo() : mvControlling->MainCtrlPos() < mvControlling->MainCtrlPosNo) { Vs = ESMVelocity(!usefieldshunting); } - if (std::abs(mvControlling->Im) < (fReady < 0.4 ? mvControlling->Imin : mvControlling->IminLo) || mvControlling->Vel > Vs) + if (std::abs(mvControlling->Im) < (fReady < 0.4 ? mvControlling->Imin() : mvControlling->IminLo) || mvControlling->Vel > Vs) { // Ra: wywalał nadmiarowy, bo Im może być ujemne; jak nie odhamowany, to nie przesadzać z prądem if (usefieldshunting) @@ -605,7 +605,7 @@ bool TController::IncSpeed() (mvControlling->RList[std::min(mvControlling->MainCtrlPos() + 1, mvControlling->MainCtrlPosNo)].Bn == 1 ? minvoltage : seriesmodevoltage) > (IsHeavyCargoTrain ? 100.0 : 75.0) * ControlledEnginesCount}; - OK = sufficientpowermargin && false == mvControlling->DelayCtrlFlag ? mvControlling->IncMainCtrl(1) : true; + OK = sufficientpowermargin && false == mvControlling->DelayCtrlFlag() ? mvControlling->IncMainCtrl(1) : true; // czekaj na 1 pozycji, zanim się nie włączą liniowe if (true == mvControlling->lineContactors.IsClosed()) { @@ -658,7 +658,7 @@ bool TController::IncSpeed() if( !IsAnyMotorOverloadRelayOpen && (Ready || drivingFlags.press || occupied->ShuntMode) ) { //{(BrakePress<=0.01*MaxBrakePress)} OK = IncSpeedEIM(); - if (mvControlling->SpeedCtrl && mvControlling->lineBreaker.IsClosed()) + if (mvControlling->SpeedCtrl() && mvControlling->lineBreaker.IsClosed()) { // cruise control auto const couplinginprogress{true == drivingFlags.connect && true == OrderCurrentGet().HasAll(DriverOrder::connect)}; @@ -679,7 +679,7 @@ bool TController::IncSpeed() case TEngineType::WheelsDriven: if (!mvControlling->CabActive) mvControlling->CabActivisation(); - if (sin(mvControlling->eAngle) > 0) + if (sin(mvControlling->eAngle()) > 0) mvControlling->IncMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); else mvControlling->DecMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); @@ -689,7 +689,7 @@ bool TController::IncSpeed() { // dla 2Ls150 można zmienić tryb pracy, jeśli jest w liniowym i nie daje rady (wymaga zerowania kierunku) // mvControlling->ShuntMode=(OrderList[OrderPos]&Shunt)||(fMass>224000.0); } - if (mvControlling->SpeedCtrl && mvControlling->lineBreaker.IsClosed()) {// cruise control + if (mvControlling->SpeedCtrl() && mvControlling->lineBreaker.IsClosed()) {// cruise control auto const couplinginprogress { true == drivingFlags.connect && true == OrderCurrentGet().HasAll(DriverOrder::connect) }; auto const SpeedCntrlVel { ( ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? @@ -708,7 +708,7 @@ bool TController::IncSpeed() if (true == Ready) { bool max = mvControlling->Vel > mvControlling->diesel.fullEngageMinVelocity - || (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos() > 0); + || (mvControlling->SpeedCtrl() && mvControlling->ScndCtrlPos() > 0); DizelPercentage = max ? 100 : 1; } break; @@ -774,7 +774,7 @@ bool TController::DecSpeed(bool force) case TEngineType::WheelsDriven: if (!mvControlling->CabActive) mvControlling->CabActivisation(); - if (sin(mvControlling->eAngle) < 0) + if (sin(mvControlling->eAngle()) < 0) mvControlling->IncMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); else mvControlling->DecMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); @@ -993,7 +993,7 @@ void TController::SpeedSet() { while( ( false == mvControlling->IsMainCtrlNoPowerPos() ) && ( mvControlling->RList[ mvControlling->MainCtrlPos() ].Bn > 1 ) ); // oporowa zapętla } - if( mvControlling->Imax < mvControlling->ImaxHi ) { // jeśli da się na wysokim + if( mvControlling->Imax < mvControlling->ImaxHi() ) { // jeśli da się na wysokim mvControlling->CurrentSwitch( true ); // rozruch wysoki (za to może się ślizgać) } if( ReactionTime > 0.1 ) { @@ -1012,7 +1012,7 @@ void TController::SpeedSet() { } // else // gdy nie jedzie ambitnie pod górę { // sprawdzenie, czy rozruch wysoki jest potrzebny - if( ( mvControlling->Imax > mvControlling->ImaxLo ) + if( ( mvControlling->Imax > mvControlling->ImaxLo() ) && ( occupied->Vel >= 30.0 ) ) { // jak się rozpędził // if (fAccGravity > -0.02) // a i pochylenie mnijsze niż 2‰ mvControlling->CurrentSwitch( false ); // rozruch wysoki wyłącz @@ -1040,7 +1040,7 @@ void TController::SpeedSet() { // jak prędkość większa niż procent maksymalnej na danym biegu, wrzucić wyższy if( velocity > 0.75 * motorparams.mfi ) { // ...presuming there is a higher gear - if( mvControlling->ScndCtrlPos() < mvControlling->ScndCtrlPosNo ) { + if( mvControlling->ScndCtrlPos() < mvControlling->ScndCtrlPosNo() ) { mvControlling->DecMainCtrl( 2 ); while( mvControlling->IncScndCtrl(1) && mvControlling->MotorParam[mvControlling->ScndCtrlPos()].mIsat == 0.0 ) { // jeśli bieg jałowy to kolejny @@ -1069,7 +1069,7 @@ void TController::SpeedSet() { void TController::SpeedCntrl(double DesiredSpeed) { - if( false == mvControlling->SpeedCtrl ) { return; } + if( false == mvControlling->SpeedCtrl() ) { return; } if (mvControlling->IsSpeedCtrlSeparate()) { @@ -1092,14 +1092,14 @@ void TController::SpeedCntrl(double DesiredSpeed) mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); } else - if (mvControlling->ScndCtrlPosNo == 1) + if (mvControlling->ScndCtrlPosNo() == 1) { mvControlling->IncScndCtrl(1); mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); } - else if (mvControlling->ScndCtrlPosNo > 1 && !occupied->SpeedCtrlTypeTime) + else if (mvControlling->ScndCtrlPosNo() > 1 && !occupied->SpeedCtrlTypeTime()) { - int DesiredPos = 1 + mvControlling->ScndCtrlPosNo * ((DesiredSpeed - 1.0) / mvControlling->Vmax); + int DesiredPos = 1 + mvControlling->ScndCtrlPosNo() * ((DesiredSpeed - 1.0) / mvControlling->Vmax()); while( mvControlling->ScndCtrlPos() > DesiredPos && true == mvControlling->DecScndCtrl(1) ) { ; } // all work is done in the condition loop while( mvControlling->ScndCtrlPos() < DesiredPos && true == mvControlling->IncScndCtrl(1) ) { ; } // all work is done in the condition loop } @@ -1175,24 +1175,24 @@ void TController::SetTimeControllers() } } */ - if( occupied->UniCtrlIntegratedLocalBrakeCtrl + if( occupied->UniCtrlIntegratedLocalBrakeCtrl() && occupied->brakes.IndependentPosition() > 0.95 ) { while( IncBrakeEIM() ) { ; } } //4. Check Speed Control System - if (occupied->EngineType == TEngineType::ElectricInductionMotor && occupied->ScndCtrlPosNo > 1 && occupied->SpeedCtrlTypeTime) + if (occupied->EngineType == TEngineType::ElectricInductionMotor && occupied->ScndCtrlPosNo() > 1 && occupied->SpeedCtrlTypeTime()) { double SpeedCntrlVel = ActualProximityDist > std::max(50.0, fMaxProximityDist) ? VelDesired : min_speed(VelDesired, VelNext); SpeedCntrlVel = 10 * std::floor(SpeedCntrlVel*0.1); - if (occupied->ScndCtrlPosNo == 4) + if (occupied->ScndCtrlPosNo() == 4) { - if (occupied->NewSpeed + 0.1 < SpeedCntrlVel) + if (occupied->NewSpeed() + 0.1 < SpeedCntrlVel) occupied->SetScndCtrlPos(3); - if (occupied->NewSpeed - 0.1 > SpeedCntrlVel) + if (occupied->NewSpeed() - 0.1 > SpeedCntrlVel) occupied->SetScndCtrlPos(1); } } @@ -1202,19 +1202,19 @@ void TController::SetTimeControllers() { DizelPercentage_Speed = DizelPercentage; //wstepnie procenty - auto MinVel{ std::min(mvControlling->torqueConverter.lockupSpeed, mvControlling->Vmax / 6) }; //minimal velocity + auto MinVel{ std::min(mvControlling->torqueConverter.lockupSpeed, mvControlling->Vmax() / 6) }; //minimal velocity //when speed controll unit is active - start with the procedure - if (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos() > 0) { + if (mvControlling->SpeedCtrl() && mvControlling->ScndCtrlPos() > 0) { if (mvControlling->ScndCtrlPos() > 0 && mvControlling->Vel < 1 + mvControlling->SpeedCtrlUnit.StartVelocity && DizelPercentage > 0) DizelPercentage_Speed = 101; //keep last position to start } else if (VelDesired > MinVel) //more power for faster ride { - auto const Factor{ 10 * mvControlling->Vmax / (mvControlling->Vmax + 3 * mvControlling->Vel) }; + auto const Factor{ 10 * mvControlling->Vmax() / (mvControlling->Vmax() + 3 * mvControlling->Vel) }; auto DesiredPercentage{ std::clamp( VelDesired > mvControlling->Vel ? (VelDesired - mvControlling->Vel) / Factor : 0, 0.0, 1.0) }; //correction for reaching desired velocity - if (VelDesired < 0.5 * mvControlling->Vmax //low velocity and reaching desired + if (VelDesired < 0.5 * mvControlling->Vmax() //low velocity and reaching desired && VelDesired - mvControlling->Vel < 10) { DesiredPercentage = std::min(DesiredPercentage, 0.75); } @@ -1258,18 +1258,18 @@ void TController::SetTimeControllers() } else //5.2. Analog direct controller - if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->Vmax > 30) + if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->Vmax() > 30) { int MaxPos = mvControlling->MainCtrlPosNo; int MinPos = MaxPos; for (int i = MaxPos; i > 1 && mvControlling->RList[i].Mn > 0; i--) MinPos = i; if (MaxPos > MinPos && mvControlling->MainCtrlPos() > 0 && AccDesired > 0) { - double Factor = 5 * mvControlling->Vmax / (mvControlling->Vmax + mvControlling->Vel); + double Factor = 5 * mvControlling->Vmax() / (mvControlling->Vmax() + mvControlling->Vel); int DesiredPos = MinPos + (MaxPos - MinPos)*(VelDesired > mvControlling->Vel ? (VelDesired - mvControlling->Vel) / Factor : 0); if (DesiredPos > MaxPos) DesiredPos = MaxPos; if (DesiredPos < MinPos) DesiredPos = MinPos; - if (!mvControlling->SlippingWheels) + if (!mvControlling->SlippingWheels()) { while (mvControlling->MainCtrlPos() > DesiredPos) mvControlling->DecMainCtrl(1); if (mvControlling->Vel>mvControlling->diesel.fullEngageMinVelocity) @@ -1361,7 +1361,7 @@ void TController::CheckTimeControllers() } } //4. Check Speed Control System - if (occupied->EngineType == TEngineType::ElectricInductionMotor && occupied->ScndCtrlPosNo > 1 && occupied->SpeedCtrlTypeTime && occupied->ScndCtrlPosNo == 4) + if (occupied->EngineType == TEngineType::ElectricInductionMotor && occupied->ScndCtrlPosNo() > 1 && occupied->SpeedCtrlTypeTime() && occupied->ScndCtrlPosNo() == 4) { occupied->SetScndCtrlPos(2); } diff --git a/vehicle/ai/driver.cpp b/vehicle/ai/driver.cpp index 5c5d33bf7..544c7e7e0 100644 --- a/vehicle/ai/driver.cpp +++ b/vehicle/ai/driver.cpp @@ -89,7 +89,7 @@ TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, fAccThreshold = is_emu() ? -0.55 : is_dmu() ? -0.45 : -0.2; /* // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors - if( ( occupied->TrainType == train_type::emu ) + if( ( occupied->TrainType() == train_type::emu ) && ( mvControlling->EngineType == TEngineType::ElectricInductionMotor ) ) { fAccThreshold += 0.10; } @@ -281,7 +281,7 @@ double TController::BrakeAccFactor() const Factor += fBrakeReaction * (/*occupied->BrakeCtrlPosR*/ BrakeCtrlPosition < 0.5 ? 1.5 : 1) * occupied->Vel / ( std::max( 0.0, ActualProximityDist ) + 1 ) * ( ( AccDesired - AbsAccS ) / fAccThreshold ); } /* - if (occupied->TrainType == train_type::dmu && occupied->Vel > 40 && VelNext<40) + if (occupied->TrainType() == train_type::dmu && occupied->Vel > 40 && VelNext<40) Factor *= 1 + 0.25 * ( (1600 - VelNext * VelNext) / (occupied->Vel * occupied->Vel) ); */ return Factor; @@ -569,10 +569,10 @@ bool TController::is_car() const { return TestFlag( occupied->CategoryFlag, 2 ); } bool TController::is_emu() const { - return mvControlling->TrainType == train_type::emu; } + return mvControlling->TrainType() == train_type::emu; } bool TController::is_dmu() const { - return mvControlling->TrainType == train_type::dmu; } + return mvControlling->TrainType() == train_type::dmu; } bool TController::has_diesel_engine() const { return mvControlling->EngineType == TEngineType::DieselElectric || mvControlling->EngineType == TEngineType::DieselEngine; } diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp index 338e8a0d6..2f0f80812 100644 --- a/vehicle/ai/force.cpp +++ b/vehicle/ai/force.cpp @@ -80,7 +80,7 @@ TController::control_tractive_and_braking_force() { return; // ...and don't touch any other controls } // if we're slipping leave the controls alone, there's a separate logic section trying to deal with it - if( true == mvControlling->SlippingWheels ) { + if( true == mvControlling->SlippingWheels() ) { return; } @@ -107,8 +107,8 @@ void TController::control_field_shunting() { if( aiControlled && mvControlling->EngineType == TEngineType::DieselElectric - && fieldshunting::has_switch( mvControlling->AutoRelayType, mvControlling->FieldShuntSwitch ) - && false == mvControlling->AutoRelayFlag ) { + && fieldshunting::has_switch( mvControlling->AutoRelayType(), mvControlling->FieldShuntSwitch() ) + && false == mvControlling->AutoRelayFlag() ) { mvControlling->AutoRelaySwitch( true ); } } @@ -216,7 +216,7 @@ void TController::control_uphill_start() { uphillStart.tractiveForce = 0.0; for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { // Ft is signed in the vehicle's own frame, and turned into the direction of travel as AbsAccS is - uphillStart.tractiveForce += std::max( 0.0, vehicle->physics->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); + uphillStart.tractiveForce += std::max( 0.0, vehicle->physics->Ft() * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); } uphillStart.holdingForce = fMass * -fAccGravity; uphill_start::situation const now { diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp index a3526b117..0826b5226 100644 --- a/vehicle/ai/physicslog.cpp +++ b/vehicle/ai/physicslog.cpp @@ -65,11 +65,11 @@ std::string TController::physicslog_line() const { std::ostringstream line; line << std::fixed << std::setprecision( 4 ) << ElapsedTime << " " - << fabs(11.31 * occupied->WheelDiameter * occupied->nrot) << " " + << fabs(11.31 * occupied->WheelDiameter() * occupied->nrot()) << " " << mvControlling->AccS() << " " << occupied->Couplers[1].Dist << " " << occupied->Couplers[1].CForce << " " - << occupied->Ft << " " + << occupied->Ft() << " " << occupied->Ff << " " << occupied->Fb << " " << occupied->brakes.cylinderPressure << " " @@ -84,7 +84,7 @@ std::string TController::physicslog_line() const { << occupied->CommandIn.Value1 << " " << occupied->CommandIn.Value2 << " " << int(mvControlling->SecuritySystem.is_blinking()) << " " - << int(mvControlling->SlippingWheels) << " " + << int(mvControlling->SlippingWheels()) << " " << mvControlling->diesel.heat.Ts << " " << mvControlling->diesel.heat.To << " " << mvControlling->diesel.heat.temperatura1 << " " @@ -114,7 +114,7 @@ void TController::PhysicsLog() #endif #if LOGPRESS == 1 std::ostringstream line; - line << ElapsedTime << "\t" << fabs(11.31 * occupied->WheelDiameter * occupied->nrot) + line << ElapsedTime << "\t" << fabs(11.31 * occupied->WheelDiameter() * occupied->nrot()) << "\t"; line << mvControlling->AccS() << "\t"; line << occupied->brakePipe.Pressure() << "\t" << occupied->brakes.controlReservoirPressure << "\t" diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp index abc3af4f6..8d99a00ad 100644 --- a/vehicle/ai/situation.cpp +++ b/vehicle/ai/situation.cpp @@ -99,7 +99,7 @@ TController::control_wheelslip() { // 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( occupied->Vel ) }; - if( mvControlling->SlippingWheels + if( mvControlling->SlippingWheels() && velocity < EU07_AI_SANDEDSTARTVELOCITY && false == mvControlling->IsMainCtrlNoPowerPos() && mvControlling->Sand > 0.0 ) { @@ -110,7 +110,7 @@ TController::control_wheelslip() { sandedStart.active = false; } // wheel slip - if( mvControlling->SlippingWheels ) { + if( mvControlling->SlippingWheels() ) { cue_action( driver_hint::sandingon ); // piasku! if( false == sandedStart.active ) { cue_action( driver_hint::tractiveforcedecrease ); @@ -125,13 +125,13 @@ TController::control_wheelslip() { cue_action( driver_hint::brakingforcedecrease ); ++iDriverFailCount; } - else if( ( std::fabs( mvControlling->Im ) > 0.75 * mvControlling->ImaxHi ) + else if( ( std::fabs( mvControlling->Im ) > 0.75 * mvControlling->ImaxHi() ) || ( sandedStart.active && false == mvControlling->IsMainCtrlNoPowerPos() ) ) { cue_action( driver_hint::sandingon ); // piaskujemy tory, coby się nie ślizgać } else { // deactivate sandbox if we aren't slipping - if( mvControlling->SandDose ) { + if( mvControlling->SandDose() ) { cue_action( driver_hint::sandingoff ); } } @@ -160,14 +160,14 @@ TController::control_pantographs() { // or the vehicle isn't shunting auto const shuntpantographsetup { OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt ) ? - occupied->AIHintShuntPantstate : + occupied->AIHintShuntPantstate() : 0 }; // raise/lower pantographs as needed auto const useregularpantographlayout { pVehicle->Next(Coupling::control) == nullptr // standalone || is_emu() // special case - || mvControlling->TrainType == train_type::et41 }; // special case + || mvControlling->TrainType() == train_type::et41 }; // special case if( occupied->Vel > EU07_AI_NOMOVEMENT ) { @@ -193,7 +193,7 @@ TController::control_pantographs() { // shunting with the pantograph setup the .fiz suggests for it control_pantographs_setup( shuntpantographsetup ); } - else if( occupied->AIHintPantstate == 0 ) { + else if( occupied->AIHintPantstate() == 0 ) { // jazda na tylnym if( iDirection >= 0 && useregularpantographlayout ) { // jak jedzie w kierunku sprzęgu 0 @@ -236,7 +236,7 @@ TController::control_pantographs() { else { // use suggested pantograph setup if( occupied->Vel > 5 ) { - auto const pantographsetup{ occupied->AIHintPantstate }; + auto const pantographsetup{ occupied->AIHintPantstate() }; cue_action( pantographsetup & 1 << 0 ? driver_hint::frontpantographvalveon : driver_hint::frontpantographvalveoff ); cue_action( @@ -404,7 +404,7 @@ TController::control_handles() { case TEngineType::ElectricSeriesMotor: { // styczniki liniowe rozłączone yBARC if( false == mvControlling->lineContactors.IsClosed() - && false == mvControlling->DelayCtrlFlag + && false == mvControlling->DelayCtrlFlag() && mvControlling->MainCtrlPowerPos() > 1 ) { cue_action( driver_hint::mastercontrollersetzerospeed ); } @@ -428,7 +428,7 @@ TController::control_handles() { case TEngineType::DieselElectric: { // styczniki liniowe rozłączone yBARC if( false == mvControlling->lineContactors.IsClosed() - && false == mvControlling->DelayCtrlFlag + && false == mvControlling->DelayCtrlFlag() && mvControlling->MainCtrlPowerPos() > 1 ) { cue_action( driver_hint::mastercontrollersetzerospeed ); } diff --git a/vehicle/ai/speed.cpp b/vehicle/ai/speed.cpp index 3d758d35c..45b3cddc2 100644 --- a/vehicle/ai/speed.cpp +++ b/vehicle/ai/speed.cpp @@ -100,7 +100,7 @@ double TController::ESMVelocity(bool Main) for (int i = 0; i < 5; i++) { MS = mvControlling->MomentumF(IF, IF, SCPN); - Fmax = MS * mvControlling->RList[MCPN].Bn * mvControlling->RList[MCPN].Mn * 2 / mvControlling->WheelDiameter * mvControlling->Transmision.Ratio; + Fmax = MS * mvControlling->RList[MCPN].Bn * mvControlling->RList[MCPN].Mn * 2 / mvControlling->WheelDiameter() * mvControlling->Transmision.Ratio; if( Fmax != 0.0 ) { IF = 0.5 * IF * ( 1 + FrictionMax / Fmax ); } @@ -111,14 +111,14 @@ 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 R = mvControlling->RList[MCPN].R + mvControlling->CircuitRes + mvControlling->RList[MCPN].Mn*mvControlling->WindingRes(); // 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; + ESMVel = ns * mvControlling->WheelDiameter()*M_PI*3.6/mvControlling->Transmision.Ratio; return ESMVel; } @@ -493,7 +493,7 @@ TController::adjust_desired_speed_for_braking_curve( double const Vel ) { VelNext * braking_distance_multiplier( static_cast( VelNext ) ) ); // both plans of a pneumatic brake are made from the brake table of the consist; with none (in shunting it isn't // worked out) the braking curve is the constant deceleration over the distance left, as before them - braking_curve::brake_table const braketable { fBrake_a0, fBrake_a1, BrakeAccTableSize, occupied->Vmax }; + braking_curve::brake_table const braketable { fBrake_a0, fBrake_a1, BrakeAccTableSize, occupied->Vmax() }; // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its // independent brake, which leaves the train brake handle where it is, kept braking earlier @@ -564,7 +564,7 @@ TController::adjust_desired_speed_for_final_approach( double const Vel ) { // cast iron blocks grip harder as the train comes to a stand braking_curve::shaped_demand( Vel, VelNext, stoppingroom, fAccGravity, - { fBrake_a0, fBrake_a1, BrakeAccTableSize, occupied->Vmax } ) : + { fBrake_a0, fBrake_a1, BrakeAccTableSize, occupied->Vmax() } ) : ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * stoppingroom ) ); if( ( fAccGravity < -0.025 ) && ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp index 0d17d4311..7677ff19a 100644 --- a/vehicle/brakesetting.cpp +++ b/vehicle/brakesetting.cpp @@ -258,7 +258,7 @@ vehicle describe(physics::Vehicle const &Vehicle, bool const Driven) { // a locomotive has Power > 1, though it may be a dead one at the end of the train described.powered = Vehicle.Power >= 1.0; described.length = Vehicle.Dim.L; - described.mass = Vehicle.TotalMass; + described.mass = Vehicle.TotalMass(); described.cut_out = is_cut_out(Vehicle) && false == Vehicle.brakes.cutOutByInspector; described.driven = Driven; return described; diff --git a/vehicle/cab/auxiliarycommands.cpp b/vehicle/cab/auxiliarycommands.cpp index fa0482117..61d419fc6 100644 --- a/vehicle/cab/auxiliarycommands.cpp +++ b/vehicle/cab/auxiliarycommands.cpp @@ -629,7 +629,7 @@ void TTrain::OnCommand_watercircuitslinktoggle(TTrain *Train, command_data const if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->controlled->WaterCircuitsLink) + if (false == Train->controlled->WaterCircuitsLink()) { // turn on OnCommand_watercircuitslinkenable(Train, Command); @@ -650,7 +650,7 @@ void TTrain::OnCommand_watercircuitslinkenable(TTrain *Train, command_data const // visual feedback Train->ggWaterCircuitsLinkButton.UpdateValue(1.0, Train->dsbSwitch); - if (true == Train->controlled->WaterCircuitsLink) + if (true == Train->controlled->WaterCircuitsLink()) { return; } // already enabled @@ -667,7 +667,7 @@ void TTrain::OnCommand_watercircuitslinkdisable(TTrain *Train, command_data cons // visual feedback Train->ggWaterCircuitsLinkButton.UpdateValue(0.0, Train->dsbSwitch); - if (false == Train->controlled->WaterCircuitsLink) + if (false == Train->controlled->WaterCircuitsLink()) { return; } // already disabled diff --git a/vehicle/cab/brakecommands.cpp b/vehicle/cab/brakecommands.cpp index 19085f5e5..afb3a6fd4 100644 --- a/vehicle/cab/brakecommands.cpp +++ b/vehicle/cab/brakecommands.cpp @@ -186,7 +186,7 @@ void TTrain::OnCommand_independentbrakebailoff(TTrain *Train, command_data const { // TODO: check if this set of conditions can be simplified. // it'd be more flexible to have an attribute indicating whether bail off position is supported - if (Train->controlled->TrainType != train_type::emu && + if (Train->controlled->TrainType() != train_type::emu && (Train->controlled->EngineType == TEngineType::ElectricSeriesMotor || Train->controlled->EngineType == TEngineType::DieselElectric || Train->controlled->EngineType == TEngineType::ElectricInductionMotor) && Train->occupied->brakes.config.handlePositions > 0) @@ -722,7 +722,7 @@ void TTrain::OnCommand_epbrakecontroltoggle(TTrain *Train, command_data const &C if (istoggle) { // switch state - if (false == Train->occupied->EpFuse) + if (false == Train->occupied->EpFuse()) { // turn on // audio feedback @@ -748,7 +748,7 @@ void TTrain::OnCommand_epbrakecontroltoggle(TTrain *Train, command_data const &C } // visual feedback Train->ggEPFuseButton.UpdateValue(ispush ? 1.0f : // push or pushtoggle - Train->occupied->EpFuse ? 1.0f : + Train->occupied->EpFuse() ? 1.0f : 0.0f, // toggle Train->dsbSwitch); } @@ -916,7 +916,7 @@ void TTrain::OnCommand_mubrakingindicatortoggle(TTrain *Train, command_data cons } return; } - if (Train->controlled->TrainType != train_type::emu) + if (Train->controlled->TrainType() != train_type::emu) { // return; diff --git a/vehicle/cab/cabcommands.cpp b/vehicle/cab/cabcommands.cpp index 6d385f9d8..b51c7a03d 100644 --- a/vehicle/cab/cabcommands.cpp +++ b/vehicle/cab/cabcommands.cpp @@ -265,7 +265,7 @@ void TTrain::OnCommand_alerteracknowledge(TTrain *Train, command_data const &Com // visual feedback Train->ggSecurityResetButton.UpdateValue(1.0, Train->dsbSwitch); - if (Train->occupied->TrainType == train_type::emu || Train->occupied->DirActive != 0) + if (Train->occupied->TrainType() == train_type::emu || Train->occupied->DirActive != 0) Train->occupied->SecuritySystem.acknowledge_press(); } else if (Command.action == GLFW_RELEASE) @@ -273,7 +273,7 @@ void TTrain::OnCommand_alerteracknowledge(TTrain *Train, command_data const &Com // visual feedback Train->ggSecurityResetButton.UpdateValue(0.0); - if (Train->occupied->TrainType == train_type::emu || Train->occupied->DirActive != 0) + if (Train->occupied->TrainType() == train_type::emu || Train->occupied->DirActive != 0) Train->occupied->SecuritySystem.acknowledge_release(); } } diff --git a/vehicle/cab/controllercommands.cpp b/vehicle/cab/controllercommands.cpp index 469030669..2d9a402c3 100644 --- a/vehicle/cab/controllercommands.cpp +++ b/vehicle/cab/controllercommands.cpp @@ -87,7 +87,7 @@ void TTrain::OnCommand_jointcontrollerset(TTrain *Train, command_data const &Com if (Command.param1 >= 0.5) { Train->set_master_controller((Command.param1 * 2 - 1) * - (Train->controlled->CoupledCtrl ? Train->controlled->MainCtrlPosNo + Train->controlled->ScndCtrlPosNo : Train->controlled->MainCtrlPosNo)); + (Train->controlled->CoupledCtrl ? Train->controlled->MainCtrlPosNo + Train->controlled->ScndCtrlPosNo() : Train->controlled->MainCtrlPosNo)); Train->m_mastercontrollerinuse = true; // when SplitEDPneumaticBrake is active the joint controller's negative range // commands the dedicated dynamic-brake lever instead of the local pneumatic brake @@ -426,7 +426,7 @@ void TTrain::OnCommand_notchingrelaytoggle(TTrain *Train, command_data const &Co if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->occupied->AutoRelayFlag) + if (false == Train->occupied->AutoRelayFlag()) { // turn on Train->occupied->AutoRelaySwitch(true); @@ -437,7 +437,7 @@ void TTrain::OnCommand_notchingrelaytoggle(TTrain *Train, command_data const &Co Train->occupied->AutoRelaySwitch(false); } // visual feedback - Train->ggAutoRelayButton.UpdateValue(Train->occupied->AutoRelayFlag ? 1.f : 0.f, Train->dsbSwitch); + Train->ggAutoRelayButton.UpdateValue(Train->occupied->AutoRelayFlag() ? 1.f : 0.f, Train->dsbSwitch); } } @@ -638,7 +638,7 @@ void TTrain::OnCommand_secondcontrollerdecreasefast(TTrain *Train, command_data void TTrain::OnCommand_secondcontrollerset(TTrain *Train, command_data const &Command) { - auto const targetposition{std::min(static_cast(Command.param1), Train->controlled->ScndCtrlPosNo)}; + auto const targetposition{std::min(static_cast(Command.param1), Train->controlled->ScndCtrlPosNo())}; // HACK: potentially animate push or pushtoggle control if (Train->ggScndCtrl.is_push()) { diff --git a/vehicle/cab/lightcommands.cpp b/vehicle/cab/lightcommands.cpp index edcbcef40..6976f6595 100644 --- a/vehicle/cab/lightcommands.cpp +++ b/vehicle/cab/lightcommands.cpp @@ -822,7 +822,7 @@ void TTrain::OnCommand_headlightdisablerearupper(TTrain *Train, command_data con void TTrain::OnCommand_modernlightdimmerincrease(TTrain *Train, command_data const &Command) { - if (!Train->occupied->enableModernDimmer) + if (!Train->occupied->enableModernDimmer()) return; // if modern dimmer is disabled, skip entire command if (Command.action == GLFW_PRESS) { @@ -841,7 +841,7 @@ void TTrain::OnCommand_modernlightdimmerincrease(TTrain *Train, command_data con } void TTrain::OnCommand_modernlightdimmerdecrease(TTrain *Train, command_data const &Command) { - if (!Train->occupied->enableModernDimmer) + if (!Train->occupied->enableModernDimmer()) return; // jeśli dimmer jest wyłączony, olewamy if (Command.action == GLFW_PRESS) @@ -1048,7 +1048,7 @@ void TTrain::OnCommand_endsignalstoggle(TTrain * /*Train*/, command_data const & void TTrain::OnCommand_headlightsdimtoggle(TTrain *Train, command_data const &Command) { - if (Train->DynamicObject->physics->enableModernDimmer) + if (Train->DynamicObject->physics->enableModernDimmer()) return; if (Command.action == GLFW_PRESS) { @@ -1069,7 +1069,7 @@ void TTrain::OnCommand_headlightsdimtoggle(TTrain *Train, command_data const &Co void TTrain::OnCommand_headlightsdimenable(TTrain *Train, command_data const &Command) { - if (Train->DynamicObject->physics->enableModernDimmer) + if (Train->DynamicObject->physics->enableModernDimmer()) return; if (Command.action == GLFW_PRESS) { @@ -1097,7 +1097,7 @@ void TTrain::OnCommand_headlightsdimenable(TTrain *Train, command_data const &Co void TTrain::OnCommand_headlightsdimdisable(TTrain *Train, command_data const &Command) { - if (Train->DynamicObject->physics->enableModernDimmer) // nie wiem dlaczego to tak dziala ze jest odwrocona logika + if (Train->DynamicObject->physics->enableModernDimmer()) // nie wiem dlaczego to tak dziala ze jest odwrocona logika return; if (Command.action == GLFW_PRESS) { diff --git a/vehicle/cab/powercommands.cpp b/vehicle/cab/powercommands.cpp index a48f1dc66..1aed10feb 100644 --- a/vehicle/cab/powercommands.cpp +++ b/vehicle/cab/powercommands.cpp @@ -468,7 +468,7 @@ void TTrain::OnCommand_motorconnectorsclose(TTrain *Train, command_data const &C void TTrain::OnCommand_motordisconnect(TTrain *Train, command_data const &Command) { - if (Train->controlled->TrainType == train_type::emu ? Train->controlled != Train->occupied : Train->iCabn != 0) + if (Train->controlled->TrainType() == train_type::emu ? Train->controlled != Train->occupied : Train->iCabn != 0) { // tylko w maszynowym return; @@ -485,7 +485,7 @@ void TTrain::OnCommand_motoroverloadrelaythresholdtoggle(TTrain *Train, command_ if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (true == Train->controlled->ShuntModeAllow ? false == Train->controlled->ShuntMode : false == Train->controlled->MotorOverloadRelayHighThreshold) + if (true == Train->controlled->ShuntModeAllow ? false == Train->controlled->ShuntMode : false == Train->controlled->MotorOverloadRelayHighThreshold()) { // turn on OnCommand_motoroverloadrelaythresholdsethigh(Train, Command); @@ -506,7 +506,7 @@ void TTrain::OnCommand_motoroverloadrelaythresholdsetlow(TTrain *Train, command_ // only reacting to press, so the switch doesn't flip back and forth if key is held down Train->controlled->CurrentSwitch(false); // visual feedback - Train->ggMaxCurrentCtrl.UpdateValue(Train->controlled->MotorOverloadRelayHighThreshold ? 1 : 0, Train->dsbSwitch); + Train->ggMaxCurrentCtrl.UpdateValue(Train->controlled->MotorOverloadRelayHighThreshold() ? 1 : 0, Train->dsbSwitch); } } @@ -518,7 +518,7 @@ void TTrain::OnCommand_motoroverloadrelaythresholdsethigh(TTrain *Train, command // only reacting to press, so the switch doesn't flip back and forth if key is held down Train->controlled->CurrentSwitch(true); // visual feedback - Train->ggMaxCurrentCtrl.UpdateValue(Train->controlled->MotorOverloadRelayHighThreshold ? 1 : 0, Train->dsbSwitch); + Train->ggMaxCurrentCtrl.UpdateValue(Train->controlled->MotorOverloadRelayHighThreshold() ? 1 : 0, Train->dsbSwitch); } } diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp index 63f37ae1b..2796e640c 100644 --- a/vehicle/cab/setup.cpp +++ b/vehicle/cab/setup.cpp @@ -75,10 +75,10 @@ bool TTrain::LoadMMediaFile(std::string const &asFileName) {"localbrakesound2:", {rsSBHissU, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, {"brakesound:", {rsBrake, internal, -1, single, sound_parameters::amplitude | sound_parameters::frequency, 100.0}}, {"fadesound:", {rsFadeSound, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"runningnoise:", {rsRunningNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax}}, - {"resonancenoise:", {rsResonanceNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax}}, - {"windsound:", {rsWindSound, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax}}, - {"huntingnoise:", {rsHuntingNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax}}, + {"runningnoise:", {rsRunningNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax()}}, + {"resonancenoise:", {rsResonanceNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax()}}, + {"windsound:", {rsWindSound, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax()}}, + {"huntingnoise:", {rsHuntingNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax()}}, {"rainsound:", {m_rainsound, internal, -1, single, 0, 100.0}}, }; for (auto &[soundname, soundsource] : internalsounds) @@ -143,23 +143,23 @@ bool TTrain::LoadMMediaFile(std::string const &asFileName) } if (rsBrake) { - rsBrake->m_frequencyfactor /= static_cast(1 + occupied->Vmax); + rsBrake->m_frequencyfactor /= static_cast(1 + occupied->Vmax()); } if (rsResonanceNoise) { - rsResonanceNoise->m_frequencyfactor /= static_cast(1 + occupied->Vmax); + rsResonanceNoise->m_frequencyfactor /= static_cast(1 + occupied->Vmax()); } if (rsWindSound) { - rsWindSound->m_frequencyfactor /= static_cast(1 + occupied->Vmax); + rsWindSound->m_frequencyfactor /= static_cast(1 + occupied->Vmax()); } if (rsRunningNoise) { - rsRunningNoise->m_frequencyfactor /= static_cast(1 + occupied->Vmax); + rsRunningNoise->m_frequencyfactor /= static_cast(1 + occupied->Vmax()); } if (rsHuntingNoise) { - rsHuntingNoise->m_frequencyfactor /= static_cast(1 + occupied->Vmax); + rsHuntingNoise->m_frequencyfactor /= static_cast(1 + occupied->Vmax()); } } std::vector>> sounds = { @@ -587,11 +587,11 @@ void TTrain::clear_cab_controls() btLampkaNadmSil.Clear(4); btLampkaStyczn.Clear(5); btLampkaPoslizg.Clear(6); - btLampkaNadmPrzetw.Clear(controlled->TrainType == train_type::emu ? -1 : 7); // EN57 nie ma tej lampki - btLampkaPrzetwOff.Clear(controlled->TrainType == train_type::emu ? 7 : -1); // za to ma tę + btLampkaNadmPrzetw.Clear(controlled->TrainType() == train_type::emu ? -1 : 7); // EN57 nie ma tej lampki + btLampkaPrzetwOff.Clear(controlled->TrainType() == train_type::emu ? 7 : -1); // za to ma tę btLampkaNadmSpr.Clear(8); btLampkaNadmWent.Clear(9); - btLampkaWysRozr.Clear(controlled->TrainType == train_type::et22 ? -1 : 10); // ET22 nie ma tej lampki + btLampkaWysRozr.Clear(controlled->TrainType() == train_type::et22 ? -1 : 10); // ET22 nie ma tej lampki btLampkaOgrzewanieSkladu.Clear(11); // overheat indicator lamps btLampkaOilOverheat.Clear(-1); @@ -999,9 +999,9 @@ void TTrain::set_cab_controls(int const Cab) ggCompressorLocalButton.PutValue(controlled->air.compressor.LocalSwitchOn() ? 1.f : 0.f); ggCompressorListButton.PutValue(static_cast(occupied->air.compressor.ListPosition() - 1)); // motor overload relay threshold / shunt mode - ggMaxCurrentCtrl.PutValue(true == controlled->ShuntModeAllow ? (true == controlled->ShuntMode ? 1.f : 0.f) : controlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); + ggMaxCurrentCtrl.PutValue(true == controlled->ShuntModeAllow ? (true == controlled->ShuntMode ? 1.f : 0.f) : controlled->MotorOverloadRelayHighThreshold() ? 1.f : 0.f); // automatic relays (AutoRelay) - ggAutoRelayButton.PutValue(occupied->AutoRelayFlag ? 1.f : 0.f); + ggAutoRelayButton.PutValue(occupied->AutoRelayFlag() ? 1.f : 0.f); // lights ggLightsButton.PutValue(static_cast(occupied->LightsPos() - 1)); @@ -1119,7 +1119,7 @@ void TTrain::set_cab_controls(int const Cab) // water heater ggWaterHeaterBreakerButton.PutValue(controlled->WaterHeater.breaker ? 1.f : 0.f); ggWaterHeaterButton.PutValue(controlled->WaterHeater.is_enabled ? 1.f : 0.f); - ggWaterCircuitsLinkButton.PutValue(controlled->WaterCircuitsLink ? 1.f : 0.f); + ggWaterCircuitsLinkButton.PutValue(controlled->WaterCircuitsLink() ? 1.f : 0.f); // fuel pump if (ggFuelPumpButton.type() != TGaugeType::push) { diff --git a/vehicle/cab/sounds.cpp b/vehicle/cab/sounds.cpp index 69b9287a8..2b7dac896 100644 --- a/vehicle/cab/sounds.cpp +++ b/vehicle/cab/sounds.cpp @@ -219,9 +219,9 @@ void TTrain::update_sounds(double const Deltatime) { auto const brakeforceratio{ - std::clamp(occupied->brakes.unitForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles * std::max(1, occupied->brakes.config.blocksPerAxle))), 0.0, 1.0)}; + std::clamp(occupied->brakes.unitForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles() * std::max(1, occupied->brakes.config.blocksPerAxle))), 0.0, 1.0)}; // HACK: in external view mute the sound rather than stop it, in case there's an opening bookend it'd (re)play on sound restart after returning inside - volume = FreeFlyModeFlag ? 0.0 : rsBrake->m_amplitudeoffset + std::sqrt(brakeforceratio * std::lerp(0.4, 1.0, occupied->Vel / (1 + occupied->Vmax))) * rsBrake->m_amplitudefactor; + volume = FreeFlyModeFlag ? 0.0 : rsBrake->m_amplitudeoffset + std::sqrt(brakeforceratio * std::lerp(0.4, 1.0, occupied->Vel / (1 + occupied->Vmax()))) * rsBrake->m_amplitudefactor; rsBrake->pitch(static_cast(rsBrake->m_frequencyoffset + occupied->Vel * rsBrake->m_frequencyfactor)); rsBrake->gain(static_cast(volume)); rsBrake->play(sound_flags::exclusive | sound_flags::looping); @@ -242,7 +242,7 @@ void TTrain::update_sounds(double const Deltatime) if (dsbSlipAlarm) { // alarm przy poslizgu dla 181/182 - BOMBARDIER - if (controlled->SlippingWheels && DynamicObject->GetVelocity() > 1.0) + if (controlled->SlippingWheels() && DynamicObject->GetVelocity() > 1.0) { dsbSlipAlarm->play(sound_flags::exclusive | sound_flags::looping); } @@ -429,11 +429,11 @@ void TTrain::update_sounds(double const Deltatime) void TTrain::update_sounds_resonancenoise(sound_source &Sound) const { // frequency calculation - auto const normalizer{occupied->Vmax * 0.01f}; + auto const normalizer{occupied->Vmax() * 0.01f}; auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * occupied->Vel * normalizer}; // volume calculation - auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(occupied->Vel / (1 + occupied->Vmax), 1.0, 0.5); // scale base volume between 0.5-1.0 + auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(occupied->Vel / (1 + occupied->Vmax()), 1.0, 0.5); // scale base volume between 0.5-1.0 if (volume > 0.05) { @@ -448,16 +448,16 @@ void TTrain::update_sounds_resonancenoise(sound_source &Sound) const void TTrain::update_sounds_runningnoise(sound_source &Sound) { // frequency calculation - auto const normalizer{(true == Sound.is_combined() ? occupied->Vmax * 0.01f : 1.f)}; + auto const normalizer{(true == Sound.is_combined() ? occupied->Vmax() * 0.01f : 1.f)}; auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * occupied->Vel * normalizer}; // volume calculation - auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(occupied->Vel / (1 + occupied->Vmax), 1.0, + auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(occupied->Vel / (1 + occupied->Vmax()), 1.0, 0.5); // scale base volume between 0.5-1.0 - if (std::abs(occupied->nrot) > 0.01) + if (std::abs(occupied->nrot()) > 0.01) { // hamulce wzmagaja halas - auto const brakeforceratio{(std::clamp(occupied->brakes.unitForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles * std::max(1, occupied->brakes.config.blocksPerAxle))), 0.0, 1.0))}; + auto const brakeforceratio{(std::clamp(occupied->brakes.unitForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles() * std::max(1, occupied->brakes.config.blocksPerAxle))), 0.0, 1.0))}; volume *= 1 + 0.125 * brakeforceratio; } diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp index 0a9394ac8..5173a40b5 100644 --- a/vehicle/cab/train.cpp +++ b/vehicle/cab/train.cpp @@ -171,7 +171,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("name", DynamicObject->asName); dict->insert("cab", occupied->CabOccupied()); dict->insert("cabactive", occupied->CabActive); - dict->insert("master", occupied->CabMaster); + dict->insert("master", occupied->CabMaster()); // basic systems state data dict->insert("battery", occupied->lowVoltage.Is24vAvailable()); dict->insert("linebreaker", controlled->lineBreaker.IsClosed()); @@ -216,7 +216,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("scnd_ctrl_actual_pos", controlled->ScndCtrlActualPos); dict->insert("brakectrl_pos", controlled->brakes.HandlePositionSmooth()); dict->insert("localbrake_pos", controlled->brakes.IndependentPosition()); - dict->insert("new_speed", occupied->NewSpeed); + dict->insert("new_speed", occupied->NewSpeed()); dict->insert("speedctrl", occupied->SpeedCtrlValue); dict->insert("speedctrlpower", occupied->SpeedCtrlUnit.DesiredPower); dict->insert("speedctrlactive", occupied->SpeedCtrlUnit.IsActive); @@ -261,9 +261,9 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("door_permit_right", occupied->Doors.instances[VehicleSide::right].open_permit); // movement data dict->insert("velocity", std::abs(occupied->Vel)); - dict->insert("tractionforce", std::abs(occupied->Ft)); - dict->insert("slipping_wheels", occupied->SlippingWheels); - dict->insert("sanding", occupied->SandDose); + dict->insert("tractionforce", std::abs(occupied->Ft())); + dict->insert("slipping_wheels", occupied->SlippingWheels()); + dict->insert("sanding", occupied->SandDose()); dict->insert("odometer", occupied->DistCounter()); // distance run in the session, km dict->insert("odometer_total", occupied->Odometer.km); // the vehicle's odometer, kept between the sessions // electric current data @@ -271,7 +271,7 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("voltage", std::abs(controlled->EngineVoltage)); dict->insert("im", std::abs(controlled->Im)); dict->insert("fuse", controlled->FuseFlag); - dict->insert("epfuse", occupied->EpFuse); + dict->insert("epfuse", occupied->EpFuse()); dict->insert("power_drawn", occupied->EnergyMeter.first); dict->insert("power_returned", occupied->EnergyMeter.second); @@ -416,7 +416,7 @@ TTrain::state_t TTrain::get_state() const static_cast(occupied->brakes.cylinderPressure), static_cast(pantographUnit->pantographAir.Pressure()), fHVoltage, - {fHCurrent[controlled->TrainType == train_type::emu ? 0 : 1], fHCurrent[2], fHCurrent[3]}, + {fHCurrent[controlled->TrainType() == train_type::emu ? 0 : 1], fHCurrent[2], fHCurrent[3]}, ggLVoltage.GetValue(), occupied->DistCounter(), static_cast(RadioChannel()), @@ -439,7 +439,7 @@ TTrain::state_t TTrain::get_state() const bool TTrain::is_eztoer() const { - return controlled->TrainType == train_type::emu && occupied->brakes.config.subsystem == TBrakeSubSystem::ss_ESt && controlled->lowVoltage.Is24vAvailable() == true && controlled->EpFuse == true && + return controlled->TrainType() == train_type::emu && occupied->brakes.config.subsystem == TBrakeSubSystem::ss_ESt && controlled->lowVoltage.Is24vAvailable() == true && controlled->EpFuse() == true && controlled->DirActive != 0; // od yB } @@ -447,7 +447,7 @@ bool TTrain::is_eztoer() const void TTrain::set_master_controller(double const Position) { - auto positionchange{std::min(static_cast(Position), controlled->CoupledCtrl ? controlled->MainCtrlPosNo + controlled->ScndCtrlPosNo : controlled->MainCtrlPosNo) - + auto positionchange{std::min(static_cast(Position), controlled->CoupledCtrl ? controlled->MainCtrlPosNo + controlled->ScndCtrlPosNo() : controlled->MainCtrlPosNo) - (controlled->CoupledCtrl ? controlled->MainCtrlPos() + controlled->ScndCtrlPos() : controlled->MainCtrlPos())}; while (positionchange < 0 && true == controlled->DecMainCtrl(1)) { @@ -515,7 +515,7 @@ void TTrain::set_train_brake_speed(TDynamicObject *Vehicle, int const Speed) void TTrain::set_paired_open_motor_connectors_button(bool const State) { - if (controlled->TrainType == train_type::et41 || controlled->TrainType == train_type::et42) + if (controlled->TrainType() == train_type::et41 || controlled->TrainType() == train_type::et42) { // crude implementation of the button affecting entire unit for multi-unit engines // TODO: rework it into part of standard command propagation system diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 333a5bce3..84f80c4b4 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -186,7 +186,7 @@ void TTrain::updateLineBreakerState(double const Deltatime) // if the button disconnecting the line breaker is down prevent the timer from accumulating fMainRelayTimer = 0.0f; } - if (m_linebreakerstate == linebreaker::state::open && fMainRelayTimer > controlled->InitialCtrlDelay) + if (m_linebreakerstate == linebreaker::state::open && fMainRelayTimer > controlled->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 @@ -245,13 +245,13 @@ void TTrain::updateDoorAndDirectionStates() m_doors = DynamicObject->Mechanik->ConsistDoorsOpen()[VehicleSide::right] || DynamicObject->Mechanik->ConsistDoorsOpen()[VehicleSide::left]; m_doorpermits = DynamicObject->Mechanik->ConsistDoorPermits()[VehicleSide::right] || DynamicObject->Mechanik->ConsistDoorPermits()[VehicleSide::left]; m_doorspermitleft = occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right].open_permit && - (simulation::Time.data().wSecond % 2 < 1 || occupied->DoorsPermitLightBlinking < 1 || - occupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->ConsistDoorsOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right] || - (occupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->ConsistDoorsOnlyOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right])); + (simulation::Time.data().wSecond % 2 < 1 || occupied->DoorsPermitLightBlinking() < 1 || + occupied->DoorsPermitLightBlinking() < 2 && DynamicObject->Mechanik->ConsistDoorsOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right] || + (occupied->DoorsPermitLightBlinking() < 3 && DynamicObject->Mechanik->ConsistDoorsOnlyOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right])); m_doorspermitright = occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left].open_permit && - (simulation::Time.data().wSecond % 2 < 1 || occupied->DoorsPermitLightBlinking < 1 || - occupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->ConsistDoorsOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left] || - (occupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->ConsistDoorsOnlyOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left])); + (simulation::Time.data().wSecond % 2 < 1 || occupied->DoorsPermitLightBlinking() < 1 || + occupied->DoorsPermitLightBlinking() < 2 && DynamicObject->Mechanik->ConsistDoorsOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left] || + (occupied->DoorsPermitLightBlinking() < 3 && DynamicObject->Mechanik->ConsistDoorsOnlyOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left])); } m_dirforward = controlled->DirActive > 0; m_dirneutral = controlled->DirActive == 0; @@ -288,7 +288,7 @@ void TTrain::processReceivedCommands() void TTrain::returnMasterController(double const Deltatime) { // nie blokujemy AI - if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag() && (occupied->TrainType == train_type::et40 || occupied->TrainType == train_type::ep05 || occupied->HasCamshaft)) + if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag() && (occupied->TrainType() == train_type::et40 || occupied->TrainType() == train_type::ep05 || occupied->HasCamshaft)) { // dla ET40 i EU05 automatyczne cofanie nastawnika - i tak nie będzie to działać dobrze... // TODO: use deltatime to stabilize speed @@ -324,12 +324,12 @@ void TTrain::updateTachometer(double const Deltatime) // McZapkie: predkosc wyswietlana na tachometrze brana jest z obrotow kol auto const maxtacho{3.0}; - double maxSpeed = controlled->Vmax * 1.05; // zachowanie starej logiki jak nie ma definicji max tarczki + double maxSpeed = controlled->Vmax() * 1.05; // zachowanie starej logiki jak nie ma definicji max tarczki if (occupied->maxTachoSpeed != 0) { maxSpeed = occupied->maxTachoSpeed; } - fTachoVelocity = static_cast(std::min(std::abs(11.31 * controlled->WheelDiameter * controlled->nrot), maxSpeed)); + fTachoVelocity = static_cast(std::min(std::abs(11.31 * controlled->WheelDiameter() * controlled->nrot()), maxSpeed)); { // skacze osobna zmienna float ff = simulation::Time.data().wSecond; // skacze co sekunde - pol sekundy // pomiar, pol sekundy ustawienie @@ -437,7 +437,7 @@ void TTrain::updateUnitStates() fPress[i][2] = static_cast(p->physics->mainPipe.Pressure()); fPress[i][3] = static_cast(p->physics->brakes.controlReservoirPressure); fPress[i][4] = static_cast(p->physics->brakes.distributor->GetBRP()); - fPress[i][5] = static_cast((p->physics->TotalMass - p->physics->Mred) * 0.001); + fPress[i][5] = static_cast((p->physics->TotalMass() - p->physics->Mred()) * 0.001); fPress[i][6] = static_cast(p->physics->brakes.spring.pressure); bBrakes[i][0] = p->physics->brakes.spring.isActive; bBrakes[i][1] = p->physics->brakes.spring.shutOff; @@ -468,7 +468,7 @@ void TTrain::updateUnitStates() } bCompressors.emplace_back(p->physics->air.compressor.IsAllowed() || p->physics->air.compressor.config.start == start_t::automatic, p->physics->air.compressor.IsRunning(), i); } - bSlip[i] = p->physics->SlippingWheels; + bSlip[i] = p->physics->SlippingWheels(); if (in < 8 && p->physics->inductionMotor.traction.maxPower > 1) { fEIMParams[1 + in][0] = static_cast(p->physics->inductionMotor.state.maxForce); @@ -496,7 +496,7 @@ void TTrain::updateUnitStates() if (in < 8 && (p->physics->EngineType == TEngineType::DieselEngine || p->physics->EngineType == TEngineType::DieselElectric)) { fDieselParams[1 + in][0] = static_cast(p->physics->enrot * 60); - fDieselParams[1 + in][1] = static_cast(p->physics->nrot); + fDieselParams[1 + in][1] = static_cast(p->physics->nrot()); fDieselParams[1 + in][2] = static_cast(p->physics->RList[p->physics->MainCtrlPos()].R); fDieselParams[1 + in][3] = static_cast(p->physics->diesel.fill); fDieselParams[1 + in][4] = static_cast(p->physics->RList[p->physics->MainCtrlPos()].Mn); @@ -591,7 +591,7 @@ void TTrain::updateFeedbackGauges() const // Ra: sterowanie miernikiem: drugi amperomierz Console::ValueSet(4, fHCurrent[2]); // pierwszy amperomierz; dla EZT prąd całkowity - Console::ValueSet(5, fHCurrent[controlled->TrainType == train_type::emu ? 0 : 1]); + Console::ValueSet(5, fHCurrent[controlled->TrainType() == train_type::emu ? 0 : 1]); // Ra: prędkość na pin 43 - wyjście analogowe (to nie jest PWM); skakanie zapewnia mechanika napędu Console::ValueSet(6, fTachoVelocity); } @@ -607,15 +607,15 @@ void TTrain::updateConverterOverload(double const Deltatime) if (controlled->converter.IsRunning() == true) { fConverterTimer += static_cast(Deltatime); - if (controlled->air.compressor.IsRunning() == true && controlled->air.compressor.config.supply == physics::CompressorSupply::converterManual && (controlled->EngineType == TEngineType::ElectricSeriesMotor || controlled->TrainType == train_type::emu) && + if (controlled->air.compressor.IsRunning() == true && controlled->air.compressor.config.supply == physics::CompressorSupply::converterManual && (controlled->EngineType == TEngineType::ElectricSeriesMotor || controlled->TrainType() == train_type::emu) && DynamicObject->Controller == Humandriver // hunter-110212: poprawka dla EZT && DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag()) { // hunter-091012: poprawka (zmiana warunku z CompressorPower /rozne od 0/ na /rowne 1/) if (fConverterTimer < fConverterPrzekaznik) { controlled->converter.Overload(); - if (controlled->TrainType != train_type::emu) - controlled->MainSwitch(false, controlled->TrainType == train_type::emu ? range_t::unit : range_t::local); + if (controlled->TrainType() != train_type::emu) + controlled->MainSwitch(false, controlled->TrainType() == train_type::emu ? range_t::unit : range_t::local); } else if (fConverterTimer >= fConverterPrzekaznik) { @@ -703,7 +703,7 @@ void TTrain::updateEngineGauges() else { int x; - if (controlled->TrainType == train_type::et42 && controlled->Imax == controlled->ImaxHi) + if (controlled->TrainType() == train_type::et42 && controlled->Imax == controlled->ImaxHi()) x = 1; else x = 2; @@ -761,10 +761,10 @@ void TTrain::updateEngineGauges() // sets the lamps of the wheel slip, the compressors, the dynamic brake permit and the active cab void TTrain::updateBasicLamps() { - if (controlled->SlippingWheels) + if (controlled->SlippingWheels()) { // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały - double veldiff = (DynamicObject->GetVelocity() - fTachoVelocity) / controlled->Vmax; + double veldiff = (DynamicObject->GetVelocity() - fTachoVelocity) / controlled->Vmax(); // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza if (veldiff < -0.01 && std::abs(controlled->Im) > 10.0) { @@ -783,7 +783,7 @@ void TTrain::updateBasicLamps() btCompressors.Turn(false); // Lampka zezwolenia na hamowanie ED - if (controlled->EpFuse) + if (controlled->EpFuse()) btEDenabled.Turn(true); else btEDenabled.Turn(false); @@ -845,7 +845,7 @@ void TTrain::updateCircuitLamps(double const Deltatime) btLampkaHamPosp.Turn(TestFlag(occupied->brakes.distributor->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania // TODO: youBy wyciągnąć flagę wysokiego stopnia btLampkaNadmWent.Turn(controlled->RventRot < 5.0 && controlled->ResistorsFlagCheck()); // hunter-121211: lampka zanikowo-pradowego wentylatorow - btLampkaWysRozr.Turn(controlled->Imax >= controlled->ImaxHi); + btLampkaWysRozr.Turn(controlled->Imax >= controlled->ImaxHi()); btLampkaNapNastHam.Turn(controlled->DirActive != 0); // napiecie na nastawniku hamulcowym btLampkaSprezarka.Turn(controlled->air.compressor.IsRunning()); // mutopsitka dziala @@ -858,11 +858,11 @@ void TTrain::updateCircuitLamps(double const Deltatime) // - pokićkał ktoś? int scp = controlled->RList[controlled->MainCtrlPos()].ScndAct; scp = scp == 255 ? 0 : scp; // Ra: whatta hella is this? - btLampkaBoczniki.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlActualPos > 0 || scp > 0); - btLampkaBocznik1.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos() > 0 || controlled->ScndCtrlActualPos > 0 || scp > 0); - btLampkaBocznik2.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos() > 1 || controlled->ScndCtrlActualPos > 1 || scp > 1); - btLampkaBocznik3.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos() > 2 || controlled->ScndCtrlActualPos > 2 || scp > 2); - btLampkaBocznik4.Turn(!controlled->DelayCtrlFlag && controlled->ScndCtrlPos() > 3 || controlled->ScndCtrlActualPos > 3 || scp > 3); + btLampkaBoczniki.Turn(!controlled->DelayCtrlFlag() && controlled->ScndCtrlActualPos > 0 || scp > 0); + btLampkaBocznik1.Turn(!controlled->DelayCtrlFlag() && controlled->ScndCtrlPos() > 0 || controlled->ScndCtrlActualPos > 0 || scp > 0); + btLampkaBocznik2.Turn(!controlled->DelayCtrlFlag() && controlled->ScndCtrlPos() > 1 || controlled->ScndCtrlActualPos > 1 || scp > 1); + btLampkaBocznik3.Turn(!controlled->DelayCtrlFlag() && controlled->ScndCtrlPos() > 2 || controlled->ScndCtrlActualPos > 2 || scp > 2); + btLampkaBocznik4.Turn(!controlled->DelayCtrlFlag() && controlled->ScndCtrlPos() > 3 || controlled->ScndCtrlActualPos > 3 || scp > 3); // biegi dla motoraka btLampkaGear1.Turn(controlled->ScndCtrlActualPos == 1 && controlled->diesel.clutchState > 0); // bieg 1 @@ -889,7 +889,7 @@ void TTrain::updateCircuitLamps(double const Deltatime) // sets the lamps of the braking, the radio, the doors, the direction, the lights and the overheating, with the low voltage on void TTrain::updateTrainLamps() { - switch (controlled->TrainType) + switch (controlled->TrainType()) { // zależnie od typu lokomotywy case train_type::emu: @@ -940,7 +940,7 @@ void TTrain::updateTrainLamps() } btLampkaDoorLockOff.Turn(false == occupied->Doors.lock_enabled); btLampkaDepartureSignal.Turn(controlled->DepartureSignal); - btLampkaNapNastHam.Turn(controlled->DirActive != 0 && occupied->EpFuse); // napiecie na nastawniku hamulcowym + btLampkaNapNastHam.Turn(controlled->DirActive != 0 && occupied->EpFuse()); // napiecie na nastawniku hamulcowym // Wylaczanie lampek kierunku gdy jedziemy // Feature uruchamiany z fiz z sekcji Ctrl. wpisem HideDirStatusWhenMoving=Yes (domyslnie No) @@ -1113,10 +1113,10 @@ void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) btLampkaStycznB.Turn(physics->LineContactorsLampLit()); // mozna prowadzic rozruch // hunter-271211: sygnalizacja poslizgu w pierwszym pojezdzie, gdy wystapi w drugim - if (physics->SlippingWheels) + if (physics->SlippingWheels()) { // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały - auto const veldiff{(DynamicObject->GetVelocity() - fTachoVelocity) / controlled->Vmax}; + auto const veldiff{(DynamicObject->GetVelocity() - fTachoVelocity) / controlled->Vmax()}; if (veldiff < -0.01) { // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza @@ -1182,7 +1182,7 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) // joint master controller moves forward to adjust power and backward to adjust brakes auto const brakerangemultiplier{/* NOTE: scaling disabled as it was conflicting with associating sounds with control positions ( controlled->CoupledCtrl ? - controlled->MainCtrlPosNo + controlled->ScndCtrlPosNo : + controlled->MainCtrlPosNo + controlled->ScndCtrlPosNo() : controlled->MainCtrlPosNo ) / static_cast(LocalBrakePosNo) */ @@ -1232,7 +1232,7 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) // Ra: od byte odejmowane boolean i konwertowane potem na double? if (false == ggScndCtrl.is_push()) { - ggScndCtrl.UpdateValue(static_cast(double(controlled->ScndCtrlPos() - (controlled->TrainType == train_type::et42 && controlled->brakes.electrodynamic.on))), dsbNastawnikBocz); + ggScndCtrl.UpdateValue(static_cast(double(controlled->ScndCtrlPos() - (controlled->TrainType() == train_type::et42 && controlled->brakes.electrodynamic.on))), dsbNastawnikBocz); } ggScndCtrl.Update(); } @@ -1254,13 +1254,13 @@ void TTrain::updateMasterControllers(bool const lowvoltagepower) } if (ggDirKey.SubModel != nullptr) { - if (controlled->TrainType != train_type::emu) + if (controlled->TrainType() != train_type::emu) { ggDirKey.UpdateValue(static_cast(double(controlled->DirActive)), dsbReverserKey); } else { - ggDirKey.UpdateValue(static_cast(double(controlled->DirActive) + double(controlled->Imin == controlled->IminHi)), dsbReverserKey); + ggDirKey.UpdateValue(static_cast(double(controlled->DirActive) + double(controlled->Imin() == controlled->IminHi)), dsbReverserKey); } ggDirKey.Update(); } @@ -1345,9 +1345,9 @@ void TTrain::updateCabSwitches(bool const lowvoltagepower) ggBrakeProfileR.Update(); ggBrakeOperationModeCtrl.Update(); ggWiperSw.Update(); - ggMaxCurrentCtrl.UpdateValue(true == controlled->ShuntModeAllow ? (true == controlled->ShuntMode ? 1.f : 0.f) : controlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); + ggMaxCurrentCtrl.UpdateValue(true == controlled->ShuntModeAllow ? (true == controlled->ShuntMode ? 1.f : 0.f) : controlled->MotorOverloadRelayHighThreshold() ? 1.f : 0.f); ggMaxCurrentCtrl.Update(); - ggAutoRelayButton.UpdateValue(occupied->AutoRelayFlag ? 1.f : 0.f); + ggAutoRelayButton.UpdateValue(occupied->AutoRelayFlag() ? 1.f : 0.f); ggAutoRelayButton.Update(); // NBMX wrzesien 2003 - drzwi ggDoorLeftPermitButton.Update(lowvoltagepower); diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp index 114c279af..d1dc4653c 100644 --- a/vehicle/dynamic/lifecycle.cpp +++ b/vehicle/dynamic/lifecycle.cpp @@ -279,7 +279,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" if( physics->brakes.config.localKind != TLocalBrake::ManualBrake ) { if( fVel < 1.0 ) { physics->IncLocalBrakeLevel( LocalBrakePosNo ); - if ( physics->EIMCtrlEmergency ) { + if ( physics->EIMCtrlEmergency() ) { physics->DecLocalBrakeLevel(1); } } @@ -566,7 +566,7 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" // McZapkie-250202 /* - iAxles = std::min( physics->NAxles, MaxAxles ); // ilość osi + iAxles = std::min( physics->NAxles(), MaxAxles ); // ilość osi */ // wczytywanie z pliku nazwatypu.mmd, w tym model erase_extension( asReplacableSkin ); @@ -717,12 +717,12 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" // McZapkie-250202 end. Track->AddDynamicObject(this); // wstawiamy do toru na pozycję 0, a potem przesuniemy // McZapkie: zmieniono na ilosc osi brane z chk - // iNumAxles=(physics->NAxles>3 ? 4 : 2 ); + // iNumAxles=(physics->NAxles()>3 ? 4 : 2 ); initial_track = MyTrack; iNumAxles = 2; // McZapkie-090402: odleglosc miedzy czopami skretu lub osiami fAxleDist = safe_clamp( - std::max( physics->BDist, physics->ADist ), + std::max( physics->BDist(), physics->ADist() ), 0.2, //żeby się dało wektory policzyć physics->Dim.L - 0.2 ); // nie mogą być za daleko bo będzie "walenie w mur" double fAxleDistHalf = fAxleDist * 0.5; @@ -738,13 +738,13 @@ TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" break; case 4: Axle0.Init(Track, this, iDirection ? 1 : -1); - Axle0.Move((iDirection ? fDist : -fDist) + (fAxleDistHalf + physics->ADist * 0.5), false); + Axle0.Move((iDirection ? fDist : -fDist) + (fAxleDistHalf + physics->ADist() * 0.5), false); Axle1.Init(Track, this, iDirection ? 1 : -1); - Axle1.Move((iDirection ? fDist : -fDist) - (fAxleDistHalf + physics->ADist * 0.5), false); + Axle1.Move((iDirection ? fDist : -fDist) - (fAxleDistHalf + physics->ADist() * 0.5), false); // Axle2.Init(Track,this,iDirection?1:-1); - // Axle2.Move((iDirection?fDist:-fDist)-(fAxleDistHalf-physics->ADist*0.5),false); + // Axle2.Move((iDirection?fDist:-fDist)-(fAxleDistHalf-physics->ADist()*0.5),false); // Axle3.Init(Track,this,iDirection?1:-1); - // Axle3.Move((iDirection?fDist:-fDist)+(fAxleDistHalf-physics->ADist*0.5),false); + // Axle3.Move((iDirection?fDist:-fDist)+(fAxleDistHalf-physics->ADist()*0.5),false); break; } // potrzebne do wyliczenia aktualnej pozycji; nie może być zero, bo nie przeliczy pozycji diff --git a/vehicle/dynamic/mmd.cpp b/vehicle/dynamic/mmd.cpp index f47093a8b..e77dacde2 100644 --- a/vehicle/dynamic/mmd.cpp +++ b/vehicle/dynamic/mmd.cpp @@ -370,7 +370,7 @@ bool TDynamicObject::loadModelsWheelKeyword( cParser &parser, std::string &token { //++iAnimatedAxles; pAnimations[i].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu pAnimations[i].yUpdate = std::bind( &TDynamicObject::UpdateAxle, this, std::placeholders::_1 ); - pAnimations[i].fMaxDist = Global.fDistanceFactor * physics->WheelDiameter * 200; + pAnimations[i].fMaxDist = Global.fDistanceFactor * physics->WheelDiameter() * 200; pAnimations[i].fMaxDist *= pAnimations[i].fMaxDist; } } @@ -381,8 +381,8 @@ bool TDynamicObject::loadModelsWheelKeyword( cParser &parser, std::string &token j = 1; k = 0; m = 0; // numer osi; kolejny znak; ile osi danego typu; która średnica - if (physics->WheelDiameterL != physics->WheelDiameter || - physics->WheelDiameterT != physics->WheelDiameter) + if (physics->WheelDiameterL != physics->WheelDiameter() || + physics->WheelDiameterT != physics->WheelDiameter()) { // obsługa różnych średnic, o ile występują while (i < iAnimType[ANIM_WHEELS] && j <= physics->AxleArangement.length()) @@ -1218,7 +1218,7 @@ bool TDynamicObject::loadSoundsBrakeKeyword( cParser &parser, std::string_view t rsBrake.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency ); rsBrake.owner( this ); // NOTE: can't pre-calculate amplitude normalization based on max brake force, as this varies depending on vehicle speed - rsBrake.m_frequencyfactor /= 1 + physics->Vmax; + rsBrake.m_frequencyfactor /= 1 + physics->Vmax(); } else if( token == "brake:" ) { @@ -1548,11 +1548,11 @@ bool TDynamicObject::loadSoundsOtherKeyword( cParser &parser, std::string_view t else if( token == "outernoise:" ) { // szum podczas jazdy: sound_source noisetemplate{ sound_placement::external, EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; - noisetemplate.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency, physics->Vmax ); + noisetemplate.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency, physics->Vmax() ); noisetemplate.owner( this ); - noisetemplate.m_amplitudefactor /= 1 + physics->Vmax; - noisetemplate.m_frequencyfactor /= 1 + physics->Vmax; + noisetemplate.m_amplitudefactor /= 1 + physics->Vmax(); + noisetemplate.m_frequencyfactor /= 1 + physics->Vmax(); #ifdef EU07_SOUND_BOGIESOUNDS if( true == m_bogiesounds.empty() ) { // fallback for cases without specified noise locations, convert sound template to a single sound source @@ -1903,7 +1903,7 @@ bool TDynamicObject::loadInternalDataDeviceKeyword( cParser &parser, std::string rsSlippery.deserialize( parser, sound_type::single, sound_parameters::amplitude ); rsSlippery.owner( this ); - rsSlippery.m_amplitudefactor /= 1 + physics->Vmax; + rsSlippery.m_amplitudefactor /= 1 + physics->Vmax(); } else { return false; diff --git a/vehicle/dynamic/movement.cpp b/vehicle/dynamic/movement.cpp index 456033b0e..d26cb101b 100644 --- a/vehicle/dynamic/movement.cpp +++ b/vehicle/dynamic/movement.cpp @@ -261,7 +261,7 @@ bool TDynamicObject::FastUpdate(double dt) if (dt == 0.0) return true; // Ra: pauza double dDOMoveLen; - if (!physics->PhysicActivation) + if (!physics->PhysicActivation()) return true; // McZapkie: wylaczanie fizyki gdy nie potrzeba if (!bEnabled) @@ -279,7 +279,7 @@ bool TDynamicObject::FastUpdate(double dt) modelRot.z }; // McZapkie: parametry powinny byc pobierane z toru // ts.R=MyTrack->fRadius; - // ts.Len= std::max(physics->BDist,physics->ADist); + // ts.Len= std::max(physics->BDist(),physics->ADist()); // ts.dHtrack=Axle1.pPosition.y-Axle0.pPosition.y; // ts.dHrail=((Axle1.GetRoll())+(Axle0.GetRoll()))*0.5f; // tp.Width=MyTrack->fTrackWidth; diff --git a/vehicle/dynamic/offtrack.cpp b/vehicle/dynamic/offtrack.cpp index 5b6b16fc9..d5aeb6668 100644 --- a/vehicle/dynamic/offtrack.cpp +++ b/vehicle/dynamic/offtrack.cpp @@ -228,7 +228,7 @@ int TDynamicObject::outward_side() const { // buckle bends the line the other way more than the curve does (the criteria of derailment, physics/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 physics->DerailAcceleration < 0.0 ? -outside : outside; + return physics->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() }; @@ -328,16 +328,16 @@ void TDynamicObject::begin_off_track() { shape.centre_of_gravity = physics->centre_of_gravity(); shape.contact_spacing = derailment::contact_spacing( physics->TrackW ); shape.base = std::max( static_cast( fAxleDist ), 1.0 ); - shape.mass = physics->TotalMass; + shape.mass = physics->TotalMass(); derail_motion::start start; start.position = vPosition; start.front = vFront; start.line = track_front(); start.speed = physics->V(); - start.reason = physics->DerailCause; - start.outward = ( physics->DerailSide != 0 ? physics->DerailSide : outward_side() ); - start.acceleration = physics->DerailAcceleration; + start.reason = physics->DerailCause(); + start.outward = ( physics->DerailSide() != 0 ? physics->DerailSide() : outward_side() ); + start.acceleration = physics->DerailAcceleration(); // the terrain as far as it may slide, and some m_offtracktotal = 0.0; @@ -467,8 +467,8 @@ void TDynamicObject::pull_neighbours( double const Distance ) { 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 ) }; + 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; } diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index c751bbb24..7bb3a9ebb 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -65,7 +65,7 @@ void TDynamicObject::RenderSounds() { if( Global.iPause != 0 ) { return; } if( m_startjoltplayed - && ( std::abs(physics->AccSVBased) < 0.01 + && ( std::abs(physics->AccSVBased()) < 0.01 || GetVelocity() < 0.01 ) ) { // if the vehicle comes to a stop set the movement jolt to play when it starts moving again m_startjoltplayed = false; @@ -366,12 +366,12 @@ void TDynamicObject::renderAirReleaseSounds( double const dt, double const brake void TDynamicObject::renderSlipAndSandSounds() { // slipping wheels - if( physics->SlippingWheels ) { + if( physics->SlippingWheels() ) { if( physics->brakes.unitForce > 100.0 && GetVelocity() > 1.0 ) { - auto const velocitydifference{ GetVelocity() / physics->Vmax }; + auto const velocitydifference{ GetVelocity() / physics->Vmax() }; rsSlippery .gain( rsSlippery.m_amplitudeoffset + rsSlippery.m_amplitudefactor * velocitydifference ) .play( sound_flags::exclusive | sound_flags::looping ); @@ -382,7 +382,7 @@ void TDynamicObject::renderSlipAndSandSounds() { } // Dzwiek piasecznicy - if( physics->SandDose ) { + if( physics->SandDose() ) { sSand.play( sound_flags::exclusive | sound_flags::looping ); } else { @@ -397,17 +397,17 @@ double TDynamicObject::renderBrakeFrictionSounds( double const dt ) { // brakes auto brakeforceratio{ 0.0 }; - if( //( false == occupied->SlippingWheels ) && + if( //( false == occupied->SlippingWheels() ) && physics->brakes.unitForce > 10.0 && physics->Vel > 0.05 ) { brakeforceratio = std::clamp( - physics->brakes.unitForce / std::max( 1.0, physics->BrakeForceR( 1.0, physics->Vel ) / ( physics->NAxles * std::max( 1, physics->brakes.config.blocksPerAxle ) ) ), + physics->brakes.unitForce / std::max( 1.0, physics->BrakeForceR( 1.0, physics->Vel ) / ( physics->NAxles() * std::max( 1, physics->brakes.config.blocksPerAxle ) ) ), 0.0, 1.0 ); rsBrake .pitch( rsBrake.m_frequencyoffset + physics->Vel * rsBrake.m_frequencyfactor ) - .gain( rsBrake.m_amplitudeoffset + std::sqrt( brakeforceratio * std::lerp( 0.4, 1.0, physics->Vel / (1 + physics->Vmax) ) ) * rsBrake.m_amplitudefactor ) + .gain( rsBrake.m_amplitudeoffset + std::sqrt( brakeforceratio * std::lerp( 0.4, 1.0, physics->Vel / (1 + physics->Vmax()) ) ) * rsBrake.m_amplitudefactor ) .play( sound_flags::exclusive | sound_flags::looping ); } else { @@ -672,7 +672,7 @@ void TDynamicObject::renderRunningNoise( double const brakeforceratio ) { // frequency calculation auto const normalizer { ( true == bogiesound.is_combined() ? - physics->Vmax * 0.01f : + physics->Vmax() * 0.01f : 1.f ) }; frequency = bogiesound.m_frequencyoffset @@ -765,8 +765,8 @@ void TDynamicObject::renderWheelFlatSound() { if( GetVelocity() > 1.0 && physics->WheelFlat() > 5.0 ) { m_wheelflat - .pitch( m_wheelflat.m_frequencyoffset + std::abs( physics->nrot ) * m_wheelflat.m_frequencyfactor ) - .gain( m_wheelflat.m_amplitudeoffset + m_wheelflat.m_amplitudefactor * ( ( 1.0 + physics->Vel / physics->Vmax + std::clamp( physics->WheelFlat() / 60.0, 0.0, 1.0 ) ) / 3.0 ) ) + .pitch( m_wheelflat.m_frequencyoffset + std::abs( physics->nrot() ) * m_wheelflat.m_frequencyfactor ) + .gain( m_wheelflat.m_amplitudeoffset + m_wheelflat.m_amplitudefactor * ( ( 1.0 + physics->Vel / physics->Vmax() + std::clamp( physics->WheelFlat() / 60.0, 0.0, 1.0 ) ) / 3.0 ) ) .play( sound_flags::exclusive | sound_flags::looping ); } else { @@ -817,7 +817,7 @@ void TDynamicObject::renderStartJoltSound() { // movement start jolt if( false == m_startjoltplayed ) { auto const velocity { GetVelocity() }; - if( ( physics->V() > 0.0 ? physics->AccSVBased > 0.1 : physics->AccSVBased < 0.1 ) + if( ( physics->V() > 0.0 ? physics->AccSVBased() > 0.1 : physics->AccSVBased() < 0.1 ) && velocity > 1.0 && velocity < 15.0 ) { m_startjolt.play( sound_flags::exclusive ); @@ -1350,7 +1350,7 @@ TDynamicObject::powertrain_sounds::renderTractionMotorSounds( physics::Vehicle c // generic traction motor sounds if( false == motors.empty() ) { - if( std::abs( Vehicle.nrot ) > 0.01 ) { + if( std::abs( Vehicle.nrot() ) > 0.01 ) { auto const &motor { motors.front() }; // frequency calculation @@ -1360,7 +1360,7 @@ TDynamicObject::powertrain_sounds::renderTractionMotorSounds( physics::Vehicle c // NOTE: we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range normalizer = 60.f * 0.01f; } - auto const motorrevolutions { std::abs( Vehicle.nrot ) * Vehicle.Transmision.Ratio }; + auto const motorrevolutions { std::abs( Vehicle.nrot() ) * Vehicle.Transmision.Ratio }; frequency = motor.m_frequencyoffset + motor.m_frequencyfactor * motorrevolutions * normalizer; diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 5b3599f3c..0cdd900bd 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -97,7 +97,7 @@ bool TDynamicObject::Update(double dt, double dt1) m_offtrackterrain.reset(); m_offtracksite.terrain( nullptr ); } - if (!physics->PhysicActivation && + if (!physics->PhysicActivation() && !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 @@ -139,7 +139,7 @@ bool TDynamicObject::Update(double dt, double dt1) updateAxleClatter( dDOMoveLen ); // fragment z EXE Kursa - /* if (physics->TrainType==train_type::et42) + /* if (physics->TrainType()==train_type::et42) { if ((physics->DynamicBrakeType=dbrake_switch) && ((physics->BrakePress > @@ -202,7 +202,7 @@ void TDynamicObject::updateTrackParameters() if( ts.R != 0.0 ) { // sin(0) results in division by zero - ts.R = -0.5 * physics->BDist / sin( ts.R * 0.5 ); + ts.R = -0.5 * physics->BDist() / sin( ts.R * 0.5 ); } } } @@ -211,7 +211,7 @@ void TDynamicObject::updateTrackParameters() // ts.R=ComputeRadius(Axle1.pPosition,Axle2.pPosition,Axle3.pPosition,Axle0.pPosition); // Ra: składową pochylenia wzdłużnego mamy policzoną w jednostkowym wektorze // vFront - ts.Len = 1.0; // std::max(physics->BDist,physics->ADist); + ts.Len = 1.0; // std::max(physics->BDist(),physics->ADist()); ts.dHtrack = -vFront.y; // Axle1.pPosition.y-Axle0.pPosition.y; //wektor // między skrajnymi osiami // (!!!odwrotny) @@ -220,7 +220,7 @@ void TDynamicObject::updateTrackParameters() 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( physics->ADist ) + Axle1.BuckleCurvature( physics->ADist ) ); + ts.buckle_curvature = 0.5 * ( Axle0.BuckleCurvature( physics->ADist() ) + Axle1.BuckleCurvature( physics->ADist() ) ); // TTrackParam tp; tp.Width = MyTrack->fTrackWidth; // McZapkie-250202 @@ -242,12 +242,12 @@ void TDynamicObject::updateCouplingState() else { physics->SetInsideConsist(false); } - if( TestFlag( physics->AIFlag, sound::attachcoupler ) ) { + if( TestFlag( physics->AIFlag(), sound::attachcoupler ) ) { auto *driver{ ctOwner ? ctOwner : Mechanik }; if( driver != nullptr ) { driver->CheckVehicles( DriverOrder::connect ); } - ClearFlag( physics->AIFlag, sound::attachcoupler ); + physics->ClearAIFlag( sound::attachcoupler ); } } @@ -309,9 +309,9 @@ void TDynamicObject::updateDriver( double const dt1 ) physics->EngineType == TEngineType::DieselElectric) && physics->EIMCtrlType > 0) { physics->CheckEIMIC(dt1); - if (physics->SpeedCtrl) + if (physics->SpeedCtrl()) physics->CheckSpeedCtrl(dt1); - physics->eimic_real = std::min(physics->eimic,physics->eimicSpeedCtrl); + physics->eimic_real = std::min(physics->eimic,physics->eimicSpeedCtrl()); physics->SendCtrlToNext(VehicleCommand::integratedController, physics->eimic_real, physics->CabActive); } if( Mechanik->primary() @@ -353,7 +353,7 @@ void TDynamicObject::switchOffMainsWithoutBattery() */ && physics->EngineType != TEngineType::DieselEngine && physics->EngineType != TEngineType::WheelsDriven ) { // jeśli bateria wyłączona, a nie diesel ani drezyna reczna - if( physics->MainSwitch( false, physics->TrainType == train_type::emu ? range_t::unit : range_t::local ) ) { + if( physics->MainSwitch( false, physics->TrainType() == train_type::emu ? range_t::unit : range_t::local ) ) { // wyłączyć zasilanie // NOTE: we turn off entire EMU, but only the affected unit for other multi-unit consists physics->RaiseEventFlag(); @@ -362,8 +362,8 @@ void TDynamicObject::switchOffMainsWithoutBattery() // TODO: have this dependant on .fiz-driven flag // NOTE: moved to pantspeed calculation part a little later in the function. all remarks and todo still apply /* - physics->PantFront( false, ( physics->TrainType == train_type::emu ? range::unit : range::local ) ); - physics->PantRear( false, ( physics->TrainType == train_type::emu ? range::unit : range::local ) ); + physics->PantFront( false, ( physics->TrainType() == train_type::emu ? range::unit : range::local ) ); + physics->PantRear( false, ( physics->TrainType() == train_type::emu ? range::unit : range::local ) ); */ } } @@ -482,7 +482,7 @@ void TDynamicObject::applyJointJolt( int const axleindex ) // the arguments keep the order they had up to 26.05.1, 0 in place of the value and the figure in place of the // upper limit, so they work out as the old clamp worked them out up to 26.05.1: the headroom is // Vmax - (Vel + 0.32 Vmax) whatever its sign, and the bump is capped from above only - double const headroom = safe_clamp( 0.0, physics->Vmax, physics->Vmax - ( physics->Vel + physics->Vmax * 0.32f ) ); + double const headroom = safe_clamp( 0.0, physics->Vmax(), physics->Vmax() - ( physics->Vel + physics->Vmax() * 0.32f ) ); double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f ); if (MyTrack->eType == tt_Normal) { @@ -505,7 +505,7 @@ void TDynamicObject::updateWheelAngles( double const dt1 ) dWheelAngle[0] += 114.59155902616464175359630962821 * physics->V() * dt1 / physics->WheelDiameterL; // przednie toczne - dWheelAngle[1] += physics->nrot * dt1 * 360.0; // napędne + dWheelAngle[1] += physics->nrot() * dt1 * 360.0; // napędne dWheelAngle[2] += 114.59155902616464175359630962821 * physics->V() * dt1 / physics->WheelDiameterT; // tylne toczne @@ -778,7 +778,7 @@ void TDynamicObject::updatePantographMotion( int const i, TAnimPant *p, double c { double k; // tymczasowy kąt if( physics->pantographAir.Pressure() > ( - physics->TrainType == train_type::emu ? + physics->TrainType() == train_type::emu ? 2.45 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 3.45 ) ) { // z EXE Kursa diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index 9643921c2..9d0e42a22 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -208,7 +208,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { auto const *physics { vehicle->physics }; if( physics->Vel < 0.01 ) { ++counts.standing[ kinds[ index ] ]; - if( ( false == road ) && physics->PhysicActivation ) { + if( ( false == road ) && physics->PhysicActivation() ) { // the test of physics::Vehicle::ComputeTotalForce(), part by part auto const moving = []( neighbour_data const &Neighbour ) { return ( Neighbour.vehicle != nullptr ) @@ -236,7 +236,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { ++counts.enabled; if( vehicle->physics->CategoryFlag & 2 ) { ++counts.road; } if( ( vehicle->Mechanik != nullptr ) && vehicle->Mechanik->AIControllFlag() ) { ++counts.ai; } - if( vehicle->physics->PhysicActivation || vehicle->MechInside ) { ++counts.active; } + if( vehicle->physics->PhysicActivation() || vehicle->MechInside ) { ++counts.active; } } Timer::subsystem.vehicles_prepare.start(); @@ -261,7 +261,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { std::size_t work { 0 }; for( std::size_t index = 0; index < m_items.size(); ++index ) { auto const *vehicle { m_items[ index ] }; - if( vehicle->physics->PhysicActivation || vehicle->MechInside ) { + if( vehicle->physics->PhysicActivation() || vehicle->MechInside ) { work += ( coarse[ index ] != 0 ? 1 : static_cast( std::max( Iterationcount, 1 ) ) ); } } @@ -374,7 +374,7 @@ derail_motion::contact_body contact_body_of( TDynamicObject const &Vehicle ) { auto const &physics { *Vehicle.physics }; derail_motion::contact_body body; - body.mass = physics.TotalMass; + body.mass = physics.TotalMass(); if( physics.OffTrack.active() ) { body.base = physics.OffTrack.base(); body.velocity = physics.OffTrack.velocity(); @@ -492,14 +492,14 @@ vehicle_table::update_off_track_contacts( double const Deltatime ) { } // one on the rails: along them into its speed, across them on its wheels, as a coupling pulls them off auto &otherPhysics { *other->physics }; - otherPhysics.SetV( otherPhysics.V() + glm::dot( impulse, otherbody.guide ) / std::max( otherPhysics.TotalMass, 1.0 ) ); + otherPhysics.SetV( otherPhysics.V() + glm::dot( impulse, otherbody.guide ) / std::max( otherPhysics.TotalMass(), 1.0 ) ); if( otherPhysics.DamageFlag.HasAll(VehicleDamage::derailed) ) { continue; } glm::dvec3 const otherleft { otherbody.guide.z, 0.0, -otherbody.guide.x }; auto const across { glm::dot( impulse, otherleft ) / Deltatime }; - auto const mass { otherPhysics.TotalMass - otherPhysics.Mred }; - auto const ratio { derail_motion::pull_ratio( std::abs( across ), 0.5 * std::numbers::pi, mass, otherPhysics.NAxles ) }; + auto const mass { otherPhysics.TotalMass() - otherPhysics.Mred() }; + auto const ratio { derail_motion::pull_ratio( std::abs( across ), 0.5 * std::numbers::pi, mass, otherPhysics.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 }; diff --git a/vehicle/dynamic/visual.cpp b/vehicle/dynamic/visual.cpp index dbbe3bf06..7beef31e2 100644 --- a/vehicle/dynamic/visual.cpp +++ b/vehicle/dynamic/visual.cpp @@ -403,7 +403,7 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) for (int i = 0; i < 4; ++i) if (smWahacze[i]) smWahacze[i]->SetRotate(float3(1, 0, 0), - fWahaczeAmp * cos(physics->eAngle)); + fWahaczeAmp * cos(physics->eAngle())); // cooling shutters // NOTE: shutters display _on state when they're closed, _off otherwise @@ -655,7 +655,7 @@ TDynamicObject::update_shake( double const Timedelta ) { if( std::abs( physics->enrot ) > 0.0 ) { // engine vibration shakevector.x += - std::sin(physics->eAngle * 4.0) * Timedelta * + std::sin(physics->eAngle() * 4.0) * Timedelta * EngineShake.scale // fade in with rpm above threshold * std::clamp( @@ -697,7 +697,7 @@ TDynamicObject::update_shake( double const Timedelta ) { shakevector += glm::dvec3( replaced.sway ? 0.0 : -physics->AccN() * Timedelta * 5.0 * Global.ShakingMultiplierRL, // highlight side sway -physics->AccVert() * Timedelta * Global.ShakingMultiplierUD, - -physics->AccSVBased * Timedelta * 1.5 * Global.ShakingMultiplierBF); // accent acceleration/deceleration + -physics->AccSVBased() * Timedelta * 1.5 * Global.ShakingMultiplierBF); // accent acceleration/deceleration // unevenness of the track under the outer axles auto const ride { 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ) * ( physics->V() * physics->V() ) }; shakevector += glm::dvec3( diff --git a/vehicle/enginestart.cpp b/vehicle/enginestart.cpp index 88f3e1dfe..1366eb43f 100644 --- a/vehicle/enginestart.cpp +++ b/vehicle/enginestart.cpp @@ -85,7 +85,7 @@ void remote_switch::update(physics::Vehicle *Engine, bool const Closeheld, bool if (Closeheld && Engine->MainSwitchCheck()) { m_heldtime += Deltatime; } - if (m_heldtime > Engine->InitialCtrlDelay) { + if (m_heldtime > Engine->InitialCtrlDelay()) { m_ready = true; } if (m_ready && false == (Closesonrelease && Closeheld)) { diff --git a/vehicle/handover.cpp b/vehicle/handover.cpp index 7361c723a..c232eb155 100644 --- a/vehicle/handover.cpp +++ b/vehicle/handover.cpp @@ -18,7 +18,7 @@ void release_ai_controls(physics::Vehicle &Occupied, physics::Vehicle &Controlli // the AI's hornoff action touches the horn only while the AI drives Occupied.SetWarningSignal(0); // the AI drives the sandbox directly, bypassing the manual and automatic sanding states - if (Controlling.SandDose && false == (Controlling.SandDoseManual || Controlling.SandDoseAuto)) { + if (Controlling.SandDose() && false == (Controlling.SandDoseManual || Controlling.SandDoseAuto)) { Controlling.Sandbox(false); } if (Occupied.DepartureSignal) { @@ -54,7 +54,7 @@ int dimmer_position(physics::Vehicle const &Occupied, bool const Headlightson) { auto const count{static_cast(positions.size())}; auto const isoff{[&positions, count](int const Position) { return Position < 0 || Position >= count || positions[Position].isOff; }}; - if (false == Occupied.enableModernDimmer || false == Headlightson || false == isoff(current)) { + if (false == Occupied.enableModernDimmer() || false == Headlightson || false == isoff(current)) { return current; } if (false == isoff(Occupied.modernDimmerDefaultPosition)) { diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index d5ac18e45..76ca721d4 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -170,9 +170,9 @@ void ui::vehicleparams_panel::render_contents() physics.MainCtrlPos(), physics.MainCtrlActualPos, std::string(isdieselinshuntmode ? to_string(physics.AnPos(), 2) + STR(" (shunt mode)") : std::to_string(physics.ScndCtrlPos()) + "(" + std::to_string(physics.ScndCtrlActualPos) + ")").c_str(), // engine - physics.EnginePower, std::abs(physics.TrainType == train_type::emu ? physics.ShowCurrent(0) : physics.Im), + physics.EnginePower, std::abs(physics.TrainType() == train_type::emu ? physics.ShowCurrent(0) : physics.Im), // revolutions - std::abs(physics.enrot) * 60, std::abs(physics.nrot) * physics.Transmision.Ratio * 60, physics.RventRot * 60, std::abs(physics.MotorBlowers[VehicleEnd::front].revolutions), + std::abs(physics.enrot) * 60, std::abs(physics.nrot()) * physics.Transmision.Ratio * 60, physics.RventRot * 60, std::abs(physics.MotorBlowers[VehicleEnd::front].revolutions), std::abs(physics.MotorBlowers[VehicleEnd::rear].revolutions), physics.diesel.heat.rpmw, physics.diesel.heat.rpmw2); ImGui::TextUnformatted(buffer.data()); @@ -180,7 +180,7 @@ void ui::vehicleparams_panel::render_contents() if (isdieselenginepowered) { std::snprintf(buffer.data(), buffer.size(), STR_C("\nTemperatures:\n engine: %.2f, oil: %.2f, water: %.2f%c%.2f"), physics.diesel.heat.Ts, physics.diesel.heat.To, physics.diesel.heat.temperatura1, - (physics.WaterCircuitsLink ? '-' : '|'), physics.diesel.heat.temperatura2); + (physics.WaterCircuitsLink() ? '-' : '|'), physics.diesel.heat.temperatura2); ImGui::TextUnformatted(buffer.data()); } @@ -221,14 +221,14 @@ void ui::vehicleparams_panel::render_contents() STR_C("Forces:\n tractive: %.1f, brake: %.1f, friction: %.2f%s\nAcceleration:\n tangential: %.2f, normal: %.2f (path radius: %s)\nVelocity: %.2f, distance traveled: %.2f\nPosition: " "[%.2f, %.2f, %.2f]"), // forces - physics.Ft * 0.001f * + physics.Ft() * 0.001f * (physics.CabActive ? physics.CabActive : vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabActive : 1) + 0.001f, - physics.Fb * 0.001f, physics.Adhesive(physics.RunningTrack.friction), (physics.SlippingWheels ? " (!)" : ""), + physics.Fb * 0.001f, physics.Adhesive(physics.RunningTrack.friction), (physics.SlippingWheels() ? " (!)" : ""), // acceleration - physics.AccSVBased, physics.AccN() + 0.001f, std::string(std::abs(physics.RunningShape.R) > 10000.0 ? "~0" : to_string(physics.RunningShape.R, 0)).c_str(), + physics.AccSVBased(), physics.AccN() + 0.001f, std::string(std::abs(physics.RunningShape.R) > 10000.0 ? "~0" : to_string(physics.RunningShape.R, 0)).c_str(), // velocity vehicle.GetVelocity(), physics.DistCounter(), // position From ef8a1fdbfd1ba73bbafa71d3b51f23c6c3c25bbf Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 13:23:53 +0100 Subject: [PATCH 27/30] refactor(physics): six more of what the rest only reads are private, under names of their own The mass of the empty vehicle, the braking force, the outcome of a derailment, the departure signal, the traction mode of a dual-mode vehicle and the moment of the motors are private to physics::Vehicle like the 53 before them, read through Mass(), Fb(), Derailed(), DepartureSignal(), TractionMode() and Mm(). Inside the class they are emptyMass, brakingForce, derailOutcome, departureSignalOn, tractionModeSetting and motorMoment, as the plain camelCase names were taken by locals there. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- application/driverhints.cpp | 14 +++++----- application/driveruipanels.cpp | 2 +- input/messaging.cpp | 2 +- physics/components/body.cpp | 36 +++++++++++++------------- physics/components/cab.cpp | 2 +- physics/components/collisions.cpp | 22 ++++++++-------- physics/components/commands.cpp | 2 +- physics/components/diesel.cpp | 10 +++---- physics/components/doors.cpp | 4 +-- physics/components/drive.cpp | 6 ++--- physics/components/fizsections.cpp | 14 +++++----- physics/components/setup.cpp | 12 ++++----- physics/components/traction.cpp | 20 +++++++------- physics/consistbraking.cpp | 2 +- physics/vehicle.h | 21 ++++++++++----- simulation/blackboxrecorder.cpp | 2 +- tests/unit/golden.cpp | 4 +-- tests/unit/invariants.cpp | 8 +++--- tests/unit/test_brake_cycle.cpp | 2 +- tests/unit/test_brakes.cpp | 4 +-- tests/unit/test_collisions.cpp | 6 ++--- tests/unit/test_commands.cpp | 2 +- tests/unit/test_crew.cpp | 4 +-- tests/unit/test_definition.cpp | 6 ++--- tests/unit/test_derail_motion.cpp | 10 +++---- tests/unit/test_derailment_vehicle.cpp | 34 ++++++++++++------------ tests/unit/test_fiz.cpp | 8 +++--- tests/unit/test_genset.cpp | 14 +++++----- tests/unit/test_handover.cpp | 6 ++--- tests/unit/test_pullee.cpp | 20 +++++++------- vehicle/ai/consist.cpp | 2 +- vehicle/ai/doors.cpp | 2 +- vehicle/ai/force.cpp | 4 +-- vehicle/ai/physicslog.cpp | 2 +- vehicle/ai/speed.cpp | 2 +- vehicle/cab/couplingcommands.cpp | 2 +- vehicle/cab/doorcommands.cpp | 4 +-- vehicle/cab/update.cpp | 2 +- vehicle/dynamic/sounds.cpp | 4 +-- vehicle/handover.cpp | 2 +- widgets/vehicleparams.cpp | 2 +- 41 files changed, 167 insertions(+), 160 deletions(-) diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 081d21862..0f9c90269 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -851,8 +851,8 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) { - return std::abs(mvControlling->Fb) <= Parameter; }, - static_cast(std::min( 0.0, 0.95 * std::abs( mvControlling->Fb ) )) ); // keep hint until 5% decrease + return std::abs(mvControlling->Fb()) <= Parameter; }, + static_cast(std::min( 0.0, 0.95 * std::abs( mvControlling->Fb() ) )) ); // keep hint until 5% decrease break; } case driver_hint::brakingforceincrease: { @@ -867,12 +867,12 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) { - return std::abs(mvControlling->Fb) > Parameter || is_equal(occupied->brakes.HandlePositionSmooth(), occupied->brakes.driverValve->GetPos(bh_EB), 0.2); }, + return std::abs(mvControlling->Fb()) > Parameter || is_equal(occupied->brakes.HandlePositionSmooth(), occupied->brakes.driverValve->GetPos(bh_EB), 0.2); }, static_cast(std::max( 0.0, std::max( - std::abs( mvControlling->Fb ) * 1.05, - std::abs( mvControlling->Fb ) + 5.0 ) )) ); + std::abs( mvControlling->Fb() ) * 1.05, + std::abs( mvControlling->Fb() ) + 5.0 ) )) ); break; } case driver_hint::brakingforcesetzero: { // releases both train and independent brake @@ -1052,7 +1052,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->Doors.has_warning == false || occupied->Doors.has_autowarning == true || occupied->DepartureSignal == true || occupied->Vel > 5.0; } ); + return occupied->Doors.has_warning == false || occupied->Doors.has_autowarning == true || occupied->DepartureSignal() == true || occupied->Vel > 5.0; } ); break; } case driver_hint::departuresignaloff: { @@ -1063,7 +1063,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return occupied->Doors.has_warning == false || occupied->Doors.has_autowarning == true || occupied->DepartureSignal == false; } ); + return occupied->Doors.has_warning == false || occupied->Doors.has_autowarning == true || occupied->DepartureSignal() == false; } ); break; } // consist doors diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index e6a8cd768..3f6c18f59 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -963,7 +963,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { STR_C("Forces:\n tractive: %.1f, brake: %.1f, drag: %.2f%s\nAcceleration:\n tangential: %.2f, normal: %.2f (path radius: %s)\nVelocity: %.2f, distance traveled: %.2f\nPosition: [%.2f, %.2f, %.2f]"), // forces physics.Ft() * 0.001f * ( physics.CabOccupied() ? physics.CabOccupied() : vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabOccupied() : 1 ) + 0.001f, - physics.Fb * 0.001f, + physics.Fb() * 0.001f, physics.FrictionForce() * 0.001f, physics.SlippingWheels() ? " (!)" : "", // acceleration diff --git a/input/messaging.cpp b/input/messaging.cpp index 4bdb39060..72ef70058 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -306,7 +306,7 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) + ( false == Vehicle->physics->Doors.instances[VehicleSide::right].is_closed ) * 32 #endif + Vehicle->physics->FuseFlag * 64 - + Vehicle->physics->DepartureSignal * 128; + + Vehicle->physics->DepartureSignal() * 128; // WriteLog("Zapisalem stare"); // WriteLog("Mam patykow "+IntToStr(t->DynamicObject->iAnimType[ANIM_PANTS])); for (int p = 0; p < 4; p++) diff --git a/physics/components/body.cpp b/physics/components/body.cpp index bfede4797..0bfd38cbf 100644 --- a/physics/components/body.cpp +++ b/physics/components/body.cpp @@ -46,7 +46,7 @@ namespace bool legacy_derailed_slides(physics::Vehicle const &Vehicle) { return Global.collisions == global_settings::collision_model::physical && TestFlag(Vehicle.CategoryFlag, 1) && Vehicle.DamageFlag.HasAll(VehicleDamage::derailed) && - Vehicle.Derailed == derailment::outcome::none; + Vehicle.Derailed() == derailment::outcome::none; } } // namespace @@ -237,10 +237,10 @@ double physics::Vehicle::ComputeMovement(double dt, double dt1, const TTrackShap // 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 (DamageFlag.HasAll(VehicleDamage::derailed) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) + if (DamageFlag.HasAll(VehicleDamage::derailed) && derailOutcome == derailment::outcome::none && false == legacy_derailed_slides(*this)) accS = -Sign(travelSpeed) * 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)) && travelSpeed == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + auto const stuck{(derailOutcome != derailment::outcome::none || legacy_derailed_slides(*this)) && travelSpeed == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; if (stuck) accS = 0.0; @@ -270,7 +270,7 @@ double physics::Vehicle::ComputeMovement(double dt, double dt1, const TTrackShap // szarpanie /* #ifdef EU07_USE_FUZZYLOGIC - if( FuzzyLogic( ( 10.0 + Track.DamageFlag ) * Mass * Vel / vmax, 500000.0, p_accn ) ) { + if( FuzzyLogic( ( 10.0 + Track.DamageFlag ) * emptyMass * Vel / vmax, 500000.0, p_accn ) ) { // Ra: czemu tu masa bez ładunku? AccV /= ( 2.0 * 0.95 + 2.0 * Random() * 0.1 ); // 95-105% of base modifier (2.0) } @@ -349,9 +349,9 @@ double physics::Vehicle::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 (DamageFlag.HasAll(VehicleDamage::derailed) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) + if (DamageFlag.HasAll(VehicleDamage::derailed) && derailOutcome == derailment::outcome::none && false == legacy_derailed_slides(*this)) accS = -Sign(travelSpeed) * g * 1; // * random(0.0, 0.1) - auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && travelSpeed == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + auto const stuck{(derailOutcome != derailment::outcome::none || legacy_derailed_slides(*this)) && travelSpeed == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; if (stuck) accS = 0.0; @@ -376,7 +376,7 @@ double physics::Vehicle::FastComputeMovement(double dt, const TTrackShape & /*Sh // 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 == DamageFlag.HasAll(VehicleDamage::derailed) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this) && Vel < 1.0) + if (true == DamageFlag.HasAll(VehicleDamage::derailed) && derailOutcome == derailment::outcome::none && false == legacy_derailed_slides(*this) && Vel < 1.0) { travelSpeed = 0.0; accS = 0.0; @@ -745,7 +745,7 @@ void physics::Vehicle::ComputeConstans(void) void physics::Vehicle::ComputeMass() { // Ra: na razie tak, ale nie wszędzie masy wirujące się wliczają - totalMass = Mass + mred; + totalMass = emptyMass + mred; if (loadAmount == 0) { @@ -812,11 +812,11 @@ void physics::Vehicle::ComputeTotalForce(double dt) FStand = FrictionForce(); // siła oporów ruchu if (true == DamageFlag.HasAll(VehicleDamage::derailed)) { - if (Derailed != derailment::outcome::none) + if (derailOutcome != 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)}; + auto const friction{OffTrack.active() ? OffTrack.friction() : derailment::sliding_friction(derailOutcome)}; FStand = friction * (totalMass - mred) * g; } else if (legacy_derailed_slides(*this)) @@ -853,9 +853,9 @@ void physics::Vehicle::ComputeTotalForce(double dt) FTrain *= FT_factor; } - Fb = BrakeForce(RunningTrack); + brakingForce = BrakeForce(RunningTrack); // poslizg - auto Fwheels{FTrain - Fb * Sign(travelSpeed)}; + auto Fwheels{FTrain - brakingForce * Sign(travelSpeed)}; if (Vel > 0.1 // crude trap, to prevent braked stationary vehicles from passing fb > mass * adhesive test && std::abs(Fwheels) > TotalMassxg * Adhesive(RunningTrack.friction)) { @@ -885,16 +885,16 @@ void physics::Vehicle::ComputeTotalForce(double dt) Fwheels = Sign(temp_nrot * M_PI * wheelDiameter - travelSpeed) * TotalMassxg * Adhesive(RunningTrack.friction); if (Fwheels * Sign(travelSpeed) > 0) { - FTrain = Fwheels + Fb * Sign(travelSpeed); + FTrain = Fwheels + brakingForce * Sign(travelSpeed); } else if (FTrain * Sign(travelSpeed) > 0) { - Fb = FTrain * Sign(travelSpeed) - Fwheels * Sign(travelSpeed); + brakingForce = FTrain * Sign(travelSpeed) - Fwheels * Sign(travelSpeed); } else { - double factor = FTrain - Fb * Sign(travelSpeed) != 0 ? Fwheels / (FTrain - Fb * Sign(travelSpeed)) : 1.0; - Fb *= factor; + double factor = FTrain - brakingForce * Sign(travelSpeed) != 0 ? Fwheels / (FTrain - brakingForce * Sign(travelSpeed)) : 1.0; + brakingForce *= factor; FTrain *= factor; } if (std::abs(nrotValue) < 0.1) @@ -930,7 +930,7 @@ void physics::Vehicle::ComputeTotalForce(double dt) } } - FStand += Fb; + FStand += brakingForce; // doliczenie składowej stycznej grawitacji FTrain /= FT_factor; FTrain += TotalMassxg * RunningShape.dHtrack; @@ -944,7 +944,7 @@ double physics::Vehicle::BrakeForceR(double ratio, double velocity) const ratio = brakes.distributor->GetBrakeRatio(ratio); if (brakes.config.maxPressureMass > 2) { - press = brakes.config.maxCylinderPressure[1] + (brakes.config.maxCylinderPressure[3] - brakes.config.maxCylinderPressure[1]) * std::min(1.0, (totalMass - Mass) / (brakes.config.maxPressureMass - Mass)); + press = brakes.config.maxCylinderPressure[1] + (brakes.config.maxCylinderPressure[3] - brakes.config.maxCylinderPressure[1]) * std::min(1.0, (totalMass - emptyMass) / (brakes.config.maxPressureMass - emptyMass)); } else { diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index 65dd87b91..c0c9c0a66 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -166,7 +166,7 @@ bool physics::Vehicle::CabDeactivisation(bool const Enforce) CabActive = 0; DirAbsolute = DirActive * CabActive; cabMaster = false; - DepartureSignal = false; // nie buczeć z nieaktywnej kabiny + departureSignalOn = false; // nie buczeć z nieaktywnej kabiny SecuritySystem.set_enabled(false); // deactivate alerter TODO: make it part of control based cab selection SendCtrlToNext(VehicleCommand::cabActivation, 0, cabOccupied); // CabActive==0! diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp index 687466138..1eaefb6e6 100644 --- a/physics/components/collisions.cpp +++ b/physics/components/collisions.cpp @@ -171,7 +171,7 @@ void physics::Vehicle::CollisionDetect(VehicleEnd const End, double const dt) // the crush, the vehicles coupled to the wall push it on (crush_hit()) auto const coupled{thiscoupler.CouplingFlag != Coupling::none}; auto const wall = [crushing, coupled](physics::Vehicle const &Vehicle) { - return Vehicle.DamageFlag.HasAll(VehicleDamage::derailed) && (false == crushing || (Vehicle.Derailed == derailment::outcome::none && false == coupled)); + return Vehicle.DamageFlag.HasAll(VehicleDamage::derailed) && (false == crushing || (Vehicle.derailOutcome == derailment::outcome::none && false == coupled)); }; if (false == wall(*this)) { @@ -259,7 +259,7 @@ void physics::Vehicle::derail_in_collision(DerailReason const Reason, std::strin return; } // upright, it slides on the sleepers and keeps passing the forces on - Derailed = derailment::outcome::off_rails; + derailOutcome = derailment::outcome::off_rails; derailCause = derail_motion::cause::collision; derailAcceleration = 0.0; derailSide = 0; @@ -372,8 +372,8 @@ bool physics::Vehicle::crush_hit(VehicleEnd const End, double const dt) // 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::none}; - auto const wall{false == coupled && DamageFlag.HasAll(VehicleDamage::derailed) && Derailed == derailment::outcome::none}; - auto const otherwall{false == coupled && othervehicle->DamageFlag.HasAll(VehicleDamage::derailed) && othervehicle->Derailed == derailment::outcome::none}; + auto const wall{false == coupled && DamageFlag.HasAll(VehicleDamage::derailed) && derailOutcome == derailment::outcome::none}; + auto const otherwall{false == coupled && othervehicle->DamageFlag.HasAll(VehicleDamage::derailed) && othervehicle->derailOutcome == derailment::outcome::none}; if (wall && otherwall) { return false; @@ -670,9 +670,9 @@ double physics::Vehicle::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 loadmass{totalMass - emptyMass - mred}; auto const loadshare{maxLoad > 0.f ? loadAmount / maxLoad : 1.0}; - return derailment::loaded_centre_of_gravity(empty, Mass, loadmass, loadshare, Floor, Dim.H); + return derailment::loaded_centre_of_gravity(empty, emptyMass, loadmass, loadshare, Floor, Dim.H); } void physics::Vehicle::check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double const Distance) @@ -734,7 +734,7 @@ void physics::Vehicle::derail(derailment::verdict const &Verdict, derailment::ve { return; } - Derailed = Verdict.result; + derailOutcome = 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; @@ -754,7 +754,7 @@ void physics::Vehicle::derail(derailment::verdict const &Verdict, derailment::ve void physics::Vehicle::rerail() { DamageFlag.Clear(VehicleDamage::derailed); - Derailed = derailment::outcome::none; + derailOutcome = 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; @@ -821,7 +821,7 @@ void physics::Vehicle::Derail(DerailReason const Reason) // 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; + derailOutcome = derailment::outcome::off_rails; derailCause = derail_motion::cause::end_of_track; derailAcceleration = 0.0; derailSide = 0; @@ -846,7 +846,7 @@ void physics::Vehicle::Derail(DerailReason const Reason) bool physics::Vehicle::leaves_track() const { - return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && DamageFlag.HasAll(VehicleDamage::derailed) && Derailed != derailment::outcome::none && + return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && DamageFlag.HasAll(VehicleDamage::derailed) && derailOutcome != derailment::outcome::none && false == OffTrack.active(); } @@ -857,7 +857,7 @@ void physics::Vehicle::pull_off(int const Side, double const Acceleration, std:: return; } // upright, its flange climbs the rail the coupling pulls it over - Derailed = derailment::outcome::off_rails; + derailOutcome = derailment::outcome::off_rails; derailCause = derail_motion::cause::pulled_off; derailAcceleration = Acceleration; derailSide = Side; diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 2fd4228da..49914bdfe 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -660,7 +660,7 @@ bool physics::Vehicle::RunDoorsCommand(VehicleCommand const Command, double CVal } else if (Command == VehicleCommand::departureSignal) { - DepartureSignal = CValue1 == 1 ? true : false; + departureSignalOn = CValue1 == 1 ? true : false; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else diff --git a/physics/components/diesel.cpp b/physics/components/diesel.cpp index 71014515d..b96e2a9dc 100644 --- a/physics/components/diesel.cpp +++ b/physics/components/diesel.cpp @@ -413,9 +413,9 @@ void physics::Vehicle::DieselElectricTractionForce(double tmp) 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 + motorMoment = Mw / Transmision.Ratio; // moment silnika trakcyjnego - Im = dieselelectric_motor_current(Mm); + Im = dieselelectric_motor_current(motorMoment); if (ShuntMode) { @@ -636,8 +636,8 @@ void physics::Vehicle::apply_dieselelectric_dynamic_brake(double const dt) ft = travelSpeed > 0.0 ? -force : travelSpeed < 0.0 ? force : 0.0; Fw = ft / nPoweredAxles; Mw = Fw * wheelDiameter / 2.0; - Mm = Mw / Transmision.Ratio; - Im = dieselelectric_motor_current(Mm); + motorMoment = Mw / Transmision.Ratio; + Im = dieselelectric_motor_current(motorMoment); EngineVoltage = 0.0; EnginePower = 0.0; } @@ -1096,7 +1096,7 @@ double physics::Vehicle::dizel_Momentum(double Fill, double n, double dt) { Moment = (diesel.maxMoment - (diesel.maxMoment - diesel.maxRevolutionsMoment) * square((enrot - diesel.maxMomentRevolutions) / (diesel.maxMomentRevolutions - diesel.maxRevolutions))) * Fill - diesel.standingMoment; } - Mm = Moment; + motorMoment = Moment; diesel.fuelConsumptionActual = diesel.fuelConsumption * enrot * Fill; diesel.fuelConsumedTotal += diesel.fuelConsumptionActual * dt / 3600.0; if (retarder.present && retarder.placement == 2) diff --git a/physics/components/doors.cpp b/physics/components/doors.cpp index 5fecf74ec..d3b796886 100644 --- a/physics/components/doors.cpp +++ b/physics/components/doors.cpp @@ -338,13 +338,13 @@ bool physics::Vehicle::LockDoors(bool const State, range_t const Notify) bool physics::Vehicle::signal_departure(bool const State, range_t const Notify) { - if (DepartureSignal == State) + if (departureSignalOn == State) { // TBD: should the command be passed to other vehicles regardless of whether it affected the primary target? return false; } - DepartureSignal = State; + departureSignalOn = State; if (Notify != range_t::local) { // wysłanie wyłączenia do pozostałych? diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp index 62543c048..4380c908d 100644 --- a/physics/components/drive.cpp +++ b/physics/components/drive.cpp @@ -321,7 +321,7 @@ public: switch (ammeter) { // do asynchronicznych case 1: - return vehicle.WindingRes() * vehicle.Mm / vehicle.Vadd; + return vehicle.WindingRes() * vehicle.Mm() / vehicle.Vadd; case 2: return vehicle.inductionMotor.forceShare * vehicle.WindingRes(); default: @@ -352,8 +352,8 @@ class DieselMechanicalDrive final : public TractionDrive public: double UpdateEnginePower(physics::Vehicle &vehicle) const override { - vehicle.diesel.power = vehicle.Mm * vehicle.enrot * (2.0 * M_PI / 1000.0); - vehicle.EnginePower = (vehicle.diesel.standingMoment + vehicle.Mm) * vehicle.enrot * (2.0 * M_PI / 1000.0); + vehicle.diesel.power = vehicle.Mm() * vehicle.enrot * (2.0 * M_PI / 1000.0); + vehicle.EnginePower = (vehicle.diesel.standingMoment + vehicle.Mm()) * vehicle.enrot * (2.0 * M_PI / 1000.0); if (vehicle.MainCtrlPowerPos() > 1) { // dodatkowe opory z powodu sprezarki} diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp index f227a5ca6..08643375c 100644 --- a/physics/components/fizsections.cpp +++ b/physics/components/fizsections.cpp @@ -57,7 +57,7 @@ int s2NNW(std::string s) void physics::Vehicle::LoadFIZ_Param(std::string const &line) { - extract_value(Mass, "M", line, "0"); + extract_value(emptyMass, "M", line, "0"); extract_value(mred, "Mred", line, "0"); extract_value(vmax, "Vmax", line, "0"); extract_value(Power, "PWR", line, "0"); @@ -606,21 +606,21 @@ void physics::Vehicle::LoadFIZ_BuffCoupl(std::string const &line, int const Inde else if (thiscoupler->CouplerType == TCouplerType::Bare) { - thiscoupler->SpringKC = 50.0 * Mass + Ftmax / 0.05; + thiscoupler->SpringKC = 50.0 * emptyMass + Ftmax / 0.05; thiscoupler->DmaxC = 0.05; - thiscoupler->FmaxC = 100.0 * Mass + 2 * Ftmax; - thiscoupler->SpringKB = 60.0 * Mass + Ftmax / 0.05; + thiscoupler->FmaxC = 100.0 * emptyMass + 2 * Ftmax; + thiscoupler->SpringKB = 60.0 * emptyMass + Ftmax / 0.05; thiscoupler->DmaxB = 0.05; - thiscoupler->FmaxB = 50.0 * Mass + 2.0 * Ftmax; + thiscoupler->FmaxB = 50.0 * emptyMass + 2.0 * Ftmax; thiscoupler->beta = 0.3; } else if (thiscoupler->CouplerType == TCouplerType::Articulated) { /* - coupler->SpringKC = 60.0 * Mass + 1000; + coupler->SpringKC = 60.0 * emptyMass + 1000; coupler->DmaxC = 0.05; coupler->FmaxC = 20000000.0 + 2.0 * Ftmax; - coupler->SpringKB = 70.0 * Mass + 1000; + coupler->SpringKB = 70.0 * emptyMass + 1000; coupler->DmaxB = 0.05; coupler->FmaxB = 4000000.0 + 2.0 * Ftmax; coupler->beta = 0.55; diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp index bd3f6b271..b6c3383c3 100644 --- a/physics/components/setup.cpp +++ b/physics/components/setup.cpp @@ -230,7 +230,7 @@ void physics::Vehicle::CreateBrakeValve() if (brakes.config.maxPressureMass < 2) // jesli przystawka wazaca brakes.distributor->SetLP(0, brakes.config.maxCylinderPressure[3], 0); else - brakes.distributor->SetLP(Mass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); + brakes.distributor->SetLP(emptyMass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); break; } case TBrakeValve::KE: @@ -241,7 +241,7 @@ void physics::Vehicle::CreateBrakeValve() if (brakes.config.maxPressureMass < 2) // jesli przystawka wazaca brakes.distributor->SetLP(0, brakes.config.maxCylinderPressure[3], 0); else - brakes.distributor->SetLP(Mass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); + brakes.distributor->SetLP(emptyMass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); break; } case TBrakeValve::NESt3: @@ -255,7 +255,7 @@ void physics::Vehicle::CreateBrakeValve() if (brakes.config.maxPressureMass < 2) // jesli przystawka wazaca brakes.distributor->SetLP(0, brakes.config.maxCylinderPressure[3], 0); else - brakes.distributor->SetLP(Mass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); + brakes.distributor->SetLP(emptyMass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); break; } case TBrakeValve::LSt: @@ -277,7 +277,7 @@ void physics::Vehicle::CreateBrakeValve() } else { - brakes.distributor->SetLP(Mass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); + brakes.distributor->SetLP(emptyMass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); } break; } @@ -285,14 +285,14 @@ void physics::Vehicle::CreateBrakeValve() { WriteLog("XBT EP2"); brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); - brakes.distributor->SetLP(Mass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); + brakes.distributor->SetLP(emptyMass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); break; } case TBrakeValve::EP1: { WriteLog("XBT EP1"); brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); - brakes.distributor->SetLP(Mass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); + brakes.distributor->SetLP(emptyMass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); brakes.distributor->SetRM(brakes.config.rapidRatio); break; } diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index 03a61a753..9af1ba69a 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -445,13 +445,13 @@ bool physics::Vehicle::MotorBlowersSwitchOff(bool State, VehicleEnd const Side, // the traction selector of a dual-mode vehicle: moves only with the line breaker open, and only where a genset is bool physics::Vehicle::TractionModeSwitch(traction_mode const Mode, range_t const Notify) { - auto const initialstate{TractionMode}; + auto const initialstate{tractionModeSetting}; // refused with the line breaker closed, and then not passed on either, so the train stays on one source auto const accepted{false == lineBreaker.IsClosed()}; if (Genset.fitted() && accepted) { - TractionMode = Mode; + tractionModeSetting = Mode; } if (Notify != range_t::local && accepted) @@ -459,7 +459,7 @@ bool physics::Vehicle::TractionModeSwitch(traction_mode const Mode, range_t cons SendCtrlToNext(VehicleCommand::tractionMode, Mode == traction_mode::genset ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); } - return TractionMode != initialstate; + return tractionModeSetting != initialstate; } // ************************************************************************************************* @@ -706,7 +706,7 @@ void physics::Vehicle::SeriesMotorTractionForce(double dt) // yB: szereg dwoch sekcji w ET42 if (trainType == train_type::et42 && Imax == imaxHi) EngineVoltage = EngineVoltage / 2.0; - Mm = Momentum(Current(enrot, EngineVoltage)); // oblicza tez prad p/slinik + motorMoment = Momentum(Current(enrot, EngineVoltage)); // oblicza tez prad p/slinik if (trainType == train_type::et42) { @@ -721,7 +721,7 @@ void physics::Vehicle::SeriesMotorTractionForce(double dt) } if (trainType == train_type::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ł + motorMoment = motorMoment * 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 @@ -736,7 +736,7 @@ void physics::Vehicle::SeriesMotorTractionForce(double dt) Itot = Im; else Itot = Im * RList[MainCtrlActualPos].Bn; // prad silnika * ilosc galezi - Mw = Mm * Transmision.Ratio * Transmision.Efficiency; + Mw = motorMoment * Transmision.Ratio * Transmision.Efficiency; Fw = Mw * 2.0 / wheelDiameter; ft = Fw * nPoweredAxles; // sila trakcyjna } @@ -789,7 +789,7 @@ void physics::Vehicle::SeriesMotorDynamicBrake(double dt) Vadd = std::min(std::max(Vadd, TUHEX_MinIw), TUHEX_MaxIw); } if (Vadd > 0) - Mm = MomentumF(Im, Vadd, 0); + motorMoment = MomentumF(Im, Vadd, 0); } // the shunt field relays of a diesel-electric, each kind its own conditions on the current, the speed or the @@ -1306,8 +1306,8 @@ void physics::Vehicle::InductionMotorDrive(double dt) // power inverters UpdateInverterFrequency(); - Mm = inductionMotor.state.torque * DirAbsolute; - Mw = Mm * Transmision.Ratio * Transmision.Efficiency; + motorMoment = inductionMotor.state.torque * DirAbsolute; + Mw = motorMoment * Transmision.Ratio * Transmision.Efficiency; Fw = Mw * 2.0 / wheelDiameter; ft = Fw * nPoweredAxles * inductionMotor.inverterRatio; inductionMotor.state.force = DirAbsolute * ft / 1000; @@ -1375,7 +1375,7 @@ void physics::Vehicle::InductionMotorOff() inv.IsActive = false; } Im = 0.0; - Mm = 0.0; + motorMoment = 0.0; Mw = 0.0; Fw = 0.0; ft = 0.0; diff --git a/physics/consistbraking.cpp b/physics/consistbraking.cpp index 455fdaa28..405008128 100644 --- a/physics/consistbraking.cpp +++ b/physics/consistbraking.cpp @@ -100,7 +100,7 @@ void physics::ConsistBrakeBlending::SumForces(Step &state, std::vectorbrakes.config.maxPressureMass + ( vehicle->brakes.config.maxPressureMass > 1.0 ? 0.0 : - vehicle->Mass ) + vehicle->Mass() ) + vehicle->Mred(); auto const Nmax = ((vehicle->brakes.config.pressureToForce * vehicle->brakes.config.maxCylinderPressure[0] - vehicle->brakes.config.cylinders.springForce) * diff --git a/physics/vehicle.h b/physics/vehicle.h index 3e6a68ab6..89395ab31 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -643,7 +643,7 @@ class Vehicle TPowerParameters LightPowerSource; /*zrodlo mocy dla oswietlenia*/ TPowerParameters AlterLightPowerSource; /*alternatywne mocy dla oswietlenia*/ double const &Vmax() const { return vmax; } - double Mass = 0.0; + double const &Mass() const { return emptyMass; } double Power = 0.0; /*max. predkosc kontrukcyjna, masa wlasna, moc*/ double const &Mred() const { return mred; } /*Ra: zredukowane masy wirujące; potrzebne do obliczeń hamowania*/ double const &TotalMass() const { return totalMass; } /*wyliczane przez ComputeMass*/ @@ -957,7 +957,7 @@ class Vehicle /*! rotacja kol [obr/s]*/ double EnginePower = 0.0; /*! chwilowa moc silnikow*/ double dL = 0.0; - double Fb = 0.0; + double const &Fb() const { return brakingForce; } double Ff = 0.0; /*przesuniecie, sila hamowania i tarcia*/ double FTrain = 0.0; double FStand = 0.0; /*! sila pociagowa i oporow ruchu*/ @@ -975,8 +975,8 @@ class Vehicle 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; } + traction_mode const &TractionMode() const { return tractionModeSetting; } + bool GensetSelected() const { return tractionModeSetting == traction_mode::genset; } water_pump WaterPump; water_heater WaterHeater; bool const &WaterCircuitsLink() const { return waterCircuitsLink; } // optional connection between water circuits @@ -1041,7 +1041,7 @@ class Vehicle double LastSwitchingTime = 0.0; /*czas ostatniego przelaczania czegos*/ int const &WarningSignal() const { return warningSignal; } // 0: nie trabi, 1,2,4: trabi void SetWarningSignal(int const Value) { warningSignal = Value; } - bool DepartureSignal = false; /*sygnal odjazdu*/ + bool const &DepartureSignal() const { return departureSignalOn; } /*sygnal odjazdu*/ bool const &InsideConsist() const { return insideConsist; } void SetInsideConsist(bool const Value) { insideConsist = Value; } /*-zmienne dla lokomotywy elektrycznej*/ @@ -1056,7 +1056,7 @@ class Vehicle double Itot = 0.0; // prad calkowity double TotalCurrent = 0.0; // momenty - double Mm = 0.0; + double const &Mm() const { return motorMoment; } double Mw = 0.0; // sily napedne double Fw = 0.0; @@ -1257,7 +1257,7 @@ class Vehicle // 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}; + derailment::outcome const &Derailed() const { return derailOutcome; } // 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 @@ -1916,6 +1916,13 @@ class Vehicle horn_supply hornSupply{horn_supply::air}; bool uniCtrlIntegratedLocalBrakeCtrl = false; double windingRes = 0.0; + // what the vehicle works out or is defined with, which the rest of the simulator only reads + double brakingForce = 0.0; + derailment::outcome derailOutcome{derailment::outcome::none}; + bool departureSignalOn = false; + double emptyMass = 0.0; + traction_mode tractionModeSetting{traction_mode::catenary}; + double motorMoment = 0.0; // the switches and the controllers the cab, the AI and the scenery change only through the operations above double travelSpeed = 0.0; TLocation location{0.0, 0.0, 0.0}; diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index 2178bcb22..15c326a49 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -81,7 +81,7 @@ std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle cons on(false == Occupied.Doors.instances[VehicleSide::right].is_closed, device::doors_right) | on(Occupied.Radio(), device::radio) | on(Controlling.trainHeating.IsOn(), device::heating) | on(Occupied.brakes.spring.isActive, device::spring_brake) | on(Controlling.ShuntMode, device::shunt_mode) | // the doors as the cab works them: the permits, the departure signal, the steps and the lock - on(Occupied.DepartureSignal, device::departure_signal) | on(Occupied.Doors.instances[VehicleSide::left].open_permit, device::door_permit_left) | + on(Occupied.DepartureSignal(), device::departure_signal) | on(Occupied.Doors.instances[VehicleSide::left].open_permit, device::door_permit_left) | on(Occupied.Doors.instances[VehicleSide::right].open_permit, device::door_permit_right) | on(Occupied.Doors.step_enabled, device::door_step) | on(Occupied.Doors.lock_enabled, device::door_lock) | on(Occupied.Doors.is_locked, device::doors_locked) | on(Occupied.brakes.distributor != nullptr && Occupied.brakes.distributor->Releaser(), device::brake_releaser) | on(Controlling.FuelPump.is_active, device::fuel_pump) | diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index 1210a7354..d083d3468 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -47,7 +47,7 @@ std::vector motion() { {"AccS", [](auto const &M) { return M.AccS(); }}, {"nrot", [](auto const &M) { return M.nrot(); }}, {"Ft", [](auto const &M) { return M.Ft(); }}, - {"Fb", [](auto const &M) { return M.Fb; }}, + {"Fb", [](auto const &M) { return M.Fb(); }}, {"FStand", [](auto const &M) { return M.FStand; }}, {"SlippingWheels", [](auto const &M) { return M.SlippingWheels() ? 1.0 : 0.0; }}, }; @@ -129,7 +129,7 @@ std::vector parameters() { {"TrainType", [](auto const &M) { return legacy_code(M.TrainType()); }}, {"EngineType", [](auto const &M) { return static_cast(M.EngineType); }}, {"Vmax", [](auto const &M) { return M.Vmax(); }}, - {"Mass", [](auto const &M) { return M.Mass; }}, + {"Mass", [](auto const &M) { return M.Mass(); }}, {"TotalMass", [](auto const &M) { return M.TotalMass(); }}, {"Mred", [](auto const &M) { return M.Mred(); }}, {"Power", [](auto const &M) { return M.Power; }}, diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index 5075299a9..caf85d879 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -41,12 +41,12 @@ std::vector const &invariants() { static std::vector const rules{ {"every value a number", [](auto const &M, double, auto const *) { - std::initializer_list const values{M.V(), M.AccS(), M.Ft(), M.Fb, M.Im, M.Itot, M.EngineVoltage, + std::initializer_list const values{M.V(), M.AccS(), M.Ft(), M.Fb(), M.Im, M.Itot, M.EngineVoltage, M.enrot, M.brakePipe.Pressure(), M.brakes.cylinderPressure, M.brakes.independentCylinderPressure, M.mainPipe.Pressure(), M.air.MainReservoirPressure(), M.lowVoltage.BatteryVoltage()}; return std::ranges::all_of(values, [](double const Value) { return std::isfinite(Value); }); }, [](auto const &M) { - return values({{"V", M.V()}, {"AccS", M.AccS()}, {"Ft", M.Ft()}, {"Fb", M.Fb}, {"Im", M.Im}, {"Itot", M.Itot}, {"EngineVoltage", M.EngineVoltage}, + return values({{"V", M.V()}, {"AccS", M.AccS()}, {"Ft", M.Ft()}, {"Fb", M.Fb()}, {"Im", M.Im}, {"Itot", M.Itot}, {"EngineVoltage", M.EngineVoltage}, {"enrot", M.enrot}, {"PipePress", M.brakePipe.Pressure()}, {"BrakePress", M.brakes.cylinderPressure}, {"LocBrakePress", M.brakes.independentCylinderPressure}, {"ScndPipePress", M.mainPipe.Pressure()}, {"Compressor", M.air.MainReservoirPressure()}, {"BatteryVoltage", M.lowVoltage.BatteryVoltage()}}); }}, @@ -115,8 +115,8 @@ std::vector const &invariants() { }, [](auto const &M) { return values({{"V", M.V()}, {"AccS", M.AccS()}}); }}, {"hand brake applied, the wheels braked on the move", - [](auto const &M, double, auto const *) { return false == M.brakes.config.hasHandBrake || M.brakes.HandBrakePosition() == 0 || std::abs(M.V()) < 0.5 || std::abs(M.Fb) > 0.0; }, - [](auto const &M) { return values({{"ManualBrakePos", M.brakes.HandBrakePosition()}, {"V", M.V()}, {"Fb", M.Fb}}); }}, + [](auto const &M, double, auto const *) { return false == M.brakes.config.hasHandBrake || M.brakes.HandBrakePosition() == 0 || std::abs(M.V()) < 0.5 || std::abs(M.Fb()) > 0.0; }, + [](auto const &M) { return values({{"ManualBrakePos", M.brakes.HandBrakePosition()}, {"V", M.V()}, {"Fb", M.Fb()}}); }}, }; return rules; } diff --git a/tests/unit/test_brake_cycle.cpp b/tests/unit/test_brake_cycle.cpp index 342cbcf6b..42e0fc2c5 100644 --- a/tests/unit/test_brake_cycle.cpp +++ b/tests/unit/test_brake_cycle.cpp @@ -185,7 +185,7 @@ TEST_CASE("brake cycle: every material of the brake shoes and disks, braking a w real.hold_brake_pipe(3.5); real.run(20.0); CHECK(real->Vel < speed - 10.0); - CHECK(real->Fb > 0.0); + CHECK(real->Fb() > 0.0); trace.mark("emergency"); real.hold_brake_pipe(0.0); real.run(60.0); diff --git a/tests/unit/test_brakes.cpp b/tests/unit/test_brakes.cpp index d4dae6f50..bd93b8ca6 100644 --- a/tests/unit/test_brakes.cpp +++ b/tests/unit/test_brakes.cpp @@ -185,7 +185,7 @@ TEST_CASE("brakes: a wagon standing braked on a gradient sleeps while the brakes wagon.hold_brake_pipe(5.0); wagon.run(60.0, slope); CHECK(wagon->brakes.cylinderPressure < 0.1); - CHECK(wagon->Fb < 1.0); + CHECK(wagon->Fb() < 1.0); CHECK(std::abs(wagon.speed()) > 1.0); CHECK(wagon->PhysicActivation()); } @@ -206,6 +206,6 @@ TEST_CASE("brakes: a wagon held by its hand brake on a gradient wakes and rolls wagon->DecManualBrakeLevel(ManualBrakePosNo); wagon.run(30.0, slope); - CHECK(wagon->Fb < 1.0); + CHECK(wagon->Fb() < 1.0); CHECK(std::abs(wagon.speed()) > 1.0); } diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp index f4222beac..e63cb6c71 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -690,7 +690,7 @@ TEST_CASE("collisions: a repaired vehicle has its ends rebuilt and is back on th auto &physics{vehicle->physics()}; physics.repair_damage(); CHECK(physics.DamageFlag.Empty()); - CHECK(physics.Derailed == derailment::outcome::none); + CHECK(physics.Derailed() == derailment::outcome::none); CHECK(physics.CollisionDerail() == NONE); CHECK(physics.pushed_off_monitor.distance() == 0.0); CHECK(physics.pushed_off_monitor.time() == 0.0); @@ -724,10 +724,10 @@ TEST_CASE("collisions: SetDamage taking the derailment off clears the collision' 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); + REQUIRE(wagon->Derailed() == derailment::outcome::off_rails); wagon->RunCommand(VehicleCommand::setDamage, DamageSet{VehicleDamage::derailed}.Bits(), -1); CHECK(wagon->CollisionDerail() == NONE); - CHECK(wagon->Derailed == derailment::outcome::none); + CHECK(wagon->Derailed() == derailment::outcome::none); CHECK_FALSE(wagon->DamageFlag.HasAll(VehicleDamage::derailed)); } diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index b06e4944d..0206fcf5d 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -60,7 +60,7 @@ std::vector state() { {"DoorLock", [](auto const &M) { return flag(M.Doors.lock_enabled); }}, {"DoorStep", [](auto const &M) { return flag(M.Doors.step_enabled); }}, {"DoorRemoteOnly", [](auto const &M) { return flag(M.Doors.remote_only); }}, - {"DepartureSignal", [](auto const &M) { return flag(M.DepartureSignal); }}, + {"DepartureSignal", [](auto const &M) { return flag(M.DepartureSignal()); }}, {"PantsValve", [](auto const &M) { return flag(M.pantographAir.valve.is_enabled) + 2 * flag(M.pantographAir.valve.is_disabled); }}, {"MaxCurrentHigh", [](auto const &M) { return flag(M.MotorOverloadRelayHighThreshold()); }}, {"Imin", [](auto const &M) { return M.Imin(); }}, diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp index 630941543..601763617 100644 --- a/tests/unit/test_crew.cpp +++ b/tests/unit/test_crew.cpp @@ -224,13 +224,13 @@ TEST_CASE("crew: what the AI held is let go when the driver leaves") { cab->SetWarningSignal(1); cab->signal_departure(true); cab->Sandbox(true); - REQUIRE(cab->DepartureSignal); + REQUIRE(cab->DepartureSignal()); REQUIRE(cab->SandDose()); crew::secure(cab.physics(), cab.physics()); CHECK(cab->WarningSignal() == 0); - CHECK_FALSE(cab->DepartureSignal); + CHECK_FALSE(cab->DepartureSignal()); CHECK_FALSE(cab->SandDose()); } diff --git a/tests/unit/test_definition.cpp b/tests/unit/test_definition.cpp index b165b741a..bfe8466e9 100644 --- a/tests/unit/test_definition.cpp +++ b/tests/unit/test_definition.cpp @@ -9,7 +9,7 @@ using test::vehicle; TEST_CASE("definition: the wagon from data/wagon.json loads with its values") { vehicle wagon{definition::load("wagon")}; - CHECK(wagon->Mass == doctest::Approx(42200.0)); + CHECK(wagon->Mass() == doctest::Approx(42200.0)); CHECK(wagon->Vmax() == doctest::Approx(120.0)); CHECK(wagon->Dim.L == doctest::Approx(26.8)); CHECK(wagon->WheelDiameter() == doctest::Approx(0.96)); @@ -21,7 +21,7 @@ TEST_CASE("definition: the wagon from data/wagon.json loads with its values") { TEST_CASE("definition: keys set by the test reach the vehicle") { vehicle heavy{definition::load("wagon").set("Param", "M", 60000).set("Wheels", "D", 1.0)}; - CHECK(heavy->Mass == doctest::Approx(60000.0)); + CHECK(heavy->Mass() == doctest::Approx(60000.0)); CHECK(heavy->WheelDiameter() == doctest::Approx(1.0)); } @@ -61,7 +61,7 @@ TEST_CASE("definition: lines the loader skips or trims: comments, a hash anywher } physics::Vehicle wagon(0.0, "wagon", "test", 0); REQUIRE(wagon.LoadFIZ_Text(crlf)); - CHECK(wagon.Mass == doctest::Approx(42200.0)); + CHECK(wagon.Mass() == doctest::Approx(42200.0)); CHECK(wagon.Vmax() == doctest::Approx(120.0)); CHECK(wagon.brakes.config.maxCylinderPressure[3] == doctest::Approx(3.8)); } diff --git a/tests/unit/test_derail_motion.cpp b/tests/unit/test_derail_motion.cpp index d114a33ad..2d3a7f1af 100644 --- a/tests/unit/test_derail_motion.cpp +++ b/tests/unit/test_derail_motion.cpp @@ -416,7 +416,7 @@ TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment n for (int step = 0; step < 10; ++step) { eu07vehicle.step(curve); } - REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + REQUIRE(eu07vehicle->Derailed() == dr::outcome::overturned); CHECK(eu07vehicle->DerailCause() == dm::cause::overturned); CHECK(eu07vehicle->DerailAcceleration() > eu07_tipping); CHECK(eu07vehicle->leaves_track()); @@ -442,7 +442,7 @@ TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment n eu07vehicle.damage_track(dtrack_norail); eu07vehicle.step(); REQUIRE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); - CHECK(eu07vehicle->Derailed == dr::outcome::off_rails); + CHECK(eu07vehicle->Derailed() == dr::outcome::off_rails); CHECK(eu07vehicle->DerailCause() == dm::cause::end_of_track); CHECK(eu07vehicle->leaves_track()); } @@ -451,7 +451,7 @@ TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment n vehicle pulled{definition::fiz("4e_v1/4e"), 40.0}; pulled->pull_off(-1, 5.0, "test"); CHECK(pulled->DamageFlag.HasAll(VehicleDamage::derailed)); - CHECK(pulled->Derailed == dr::outcome::off_rails); + CHECK(pulled->Derailed() == dr::outcome::off_rails); CHECK(pulled->DerailCause() == dm::cause::pulled_off); CHECK(pulled->DerailSide() == -1); CHECK(pulled->leaves_track()); @@ -474,7 +474,7 @@ TEST_CASE("derail motion: with physics.derailment monitor and old the vehicle st fast.step(curve); } REQUIRE(fast->DamageFlag.HasAll(VehicleDamage::derailed)); - CHECK(fast->Derailed == dr::outcome::none); + CHECK(fast->Derailed() == dr::outcome::none); CHECK_FALSE(fast->leaves_track()); CHECK_FALSE(fast->OffTrack.active()); // stopped dead by the legacy model @@ -483,7 +483,7 @@ TEST_CASE("derail motion: with physics.derailment monitor and old the vehicle st ending.damage_track(dtrack_norail); ending.step(); REQUIRE(ending->DamageFlag.HasAll(VehicleDamage::derailed)); - CHECK(ending->Derailed == dr::outcome::none); + 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}; diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp index 24efb30a8..bbd8d4af8 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -48,7 +48,7 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { eu07vehicle.step(curve); } CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); - CHECK(eu07vehicle->Derailed == dr::outcome::none); + 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}; @@ -58,7 +58,7 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { eu07vehicle.step(curve); } REQUIRE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); - CHECK(eu07vehicle->Derailed == dr::outcome::overturned); + CHECK(eu07vehicle->Derailed() == dr::outcome::overturned); CHECK_FALSE(eu07vehicle->lineBreaker.IsClosed()); // 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()}; @@ -79,7 +79,7 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { for (int step = 0; step < 50; ++step) { high.step(curve); } - CHECK(high->Derailed == dr::outcome::overturned); + 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}) { @@ -89,12 +89,12 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { for (auto step = 0; step < steps; ++step) { eu07vehicle.step(curve, dt); } - CHECK(eu07vehicle->Derailed == dr::outcome::overturned); + 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); + CHECK(slower->Derailed() == dr::outcome::none); } } SUBCASE("a load raises the centre of gravity") { @@ -126,7 +126,7 @@ TEST_CASE("derailment: the model of eu07.ini") { } // far over its threshold the draw comes out at once CHECK(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); - CHECK(eu07vehicle->Derailed == dr::outcome::none); + CHECK(eu07vehicle->Derailed() == dr::outcome::none); CHECK(eu07vehicle->V() == doctest::Approx(0.0).epsilon(0.01)); } } @@ -140,7 +140,7 @@ TEST_CASE("derailment: the brake hoses tear") { for (int step = 0; step < 20; ++step) { eu07vehicle.step(curve); } - REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + REQUIRE(eu07vehicle->Derailed() == dr::outcome::overturned); CHECK(eu07vehicle->brakes.alarmChain); } @@ -155,7 +155,7 @@ TEST_CASE("derailment: a stopped derailed vehicle stays put on a gradient") { for (int step = 0; step < 2000; ++step) { eu07vehicle.step(curve); } - REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + REQUIRE(eu07vehicle->Derailed() == dr::outcome::overturned); REQUIRE(eu07vehicle->V() == 0.0); auto still{true}; for (int step = 0; step < 500; ++step) { @@ -177,11 +177,11 @@ TEST_CASE("derailment: a repaired vehicle is back on the rails") { for (int step = 0; step < 2000; ++step) { repaired.step(curve); } - REQUIRE(repaired->Derailed == dr::outcome::overturned); + REQUIRE(repaired->Derailed() == dr::outcome::overturned); REQUIRE(repaired->V() == 0.0); repaired->repair_damage(); CHECK(repaired->DamageFlag.Empty()); - CHECK(repaired->Derailed == dr::outcome::none); + CHECK(repaired->Derailed() == dr::outcome::none); CHECK(repaired->DerailmentDistance() == 0.0); CHECK(repaired->OffsetTrackH() == 0.0); CHECK(repaired->OffsetTrackV() == 0.0); @@ -193,7 +193,7 @@ TEST_CASE("derailment: a repaired vehicle is back on the rails") { repaired->SetAccS(0.0); repaired->Derail(TOO_HIGH_SPEED); fresh->Derail(TOO_HIGH_SPEED); - REQUIRE(repaired->Derailed == dr::outcome::none); + REQUIRE(repaired->Derailed() == dr::outcome::none); auto const start{fresh->V()}; REQUIRE(start > 10.0); for (int step = 0; step < 150; ++step) { @@ -221,7 +221,7 @@ TEST_CASE("derailment: a repaired vehicle is back on the rails") { for (int step = 0; step < 20; ++step) { repaired.step(curve); } - CHECK(repaired->Derailed == dr::outcome::overturned); + CHECK(repaired->Derailed() == dr::outcome::overturned); } } @@ -233,14 +233,14 @@ TEST_CASE("derailment: SetDamage taking the derailment off puts the vehicle back for (int step = 0; step < 20; ++step) { eu07vehicle.step(curve); } - REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + REQUIRE(eu07vehicle->Derailed() == dr::outcome::overturned); // another flag taken off leaves it derailed eu07vehicle->RunCommand(VehicleCommand::setDamage, DamageSet{VehicleDamage::engine}.Bits(), 1); eu07vehicle->RunCommand(VehicleCommand::setDamage, DamageSet{VehicleDamage::engine}.Bits(), -1); - CHECK(eu07vehicle->Derailed == dr::outcome::overturned); + CHECK(eu07vehicle->Derailed() == dr::outcome::overturned); CHECK(eu07vehicle->RunCommand(VehicleCommand::setDamage, DamageSet{VehicleDamage::derailed}.Bits(), -1)); CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); - CHECK(eu07vehicle->Derailed == dr::outcome::none); + CHECK(eu07vehicle->Derailed() == dr::outcome::none); } TEST_CASE("derailment: monitor tells again on the same track after a repair") { @@ -275,7 +275,7 @@ TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what t eu07vehicle.step(curve); } CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); - CHECK(eu07vehicle->Derailed == dr::outcome::none); + 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()); @@ -302,7 +302,7 @@ TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what t faster.step(curve); } CHECK(faster->DamageFlag.HasAll(VehicleDamage::derailed)); - CHECK(faster->Derailed == dr::outcome::none); + CHECK(faster->Derailed() == dr::outcome::none); CHECK(faster->V() == doctest::Approx(0.0).epsilon(0.01)); } } diff --git a/tests/unit/test_fiz.cpp b/tests/unit/test_fiz.cpp index 51488f5de..2cf5c8246 100644 --- a/tests/unit/test_fiz.cpp +++ b/tests/unit/test_fiz.cpp @@ -25,8 +25,8 @@ TEST_CASE("fiz: every real vehicle loads and keeps its parameters") { test::trace trace{"fiz/" + path, test::channels::parameters(), 1}; trace.sample(0.0, real.physics()); // what every vehicle has, the rest of its parameters are in the golden trace - CHECK(real->Mass > 0.0); - CHECK(real->TotalMass() >= real->Mass); + CHECK(real->Mass() > 0.0); + CHECK(real->TotalMass() >= real->Mass()); CHECK(real->Vmax() > 0.0); CHECK(real->NAxles() > 0); CHECK(real->WheelDiameter() > 0.0); @@ -37,8 +37,8 @@ TEST_CASE("fiz: every real vehicle loads and keeps its parameters") { TEST_CASE("fiz: changes made by a test reach the vehicle") { auto const eu07{definition::fiz("4e_v1/4e")}; - CHECK(vehicle{eu07}->Mass == doctest::Approx(80000.0)); - CHECK(vehicle{definition{eu07}.set("Param", "M", 90000)}->Mass == doctest::Approx(90000.0)); + CHECK(vehicle{eu07}->Mass() == doctest::Approx(80000.0)); + CHECK(vehicle{definition{eu07}.set("Param", "M", 90000)}->Mass() == doctest::Approx(90000.0)); // a key the file doesn't have is added to its section CHECK(vehicle{definition{eu07}.set("Brake", "MaxBP", 3.5)}->brakes.config.maxCylinderPressure[3] == doctest::Approx(3.5)); // removing a key brings its default back diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp index b26654f8d..b6211fa35 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -130,7 +130,7 @@ TEST_CASE("genset: a vehicle without the keys has none and stays on the catenary 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(cab.TractionMode() == traction_mode::catenary); CHECK_FALSE(cab.GensetSelected()); REQUIRE(test::start_up(test::driving(dragon6), wire)); CHECK(cab.pantographCircuit.SupplyVoltage() > 2900.0); @@ -142,7 +142,7 @@ TEST_CASE("genset: a vehicle without the keys has none and stays on the catenary run(dragon6, 20.0, wire); CHECK_FALSE(cab.Genset.is_active); CHECK(cab.Genset.voltage == 0.0); - CHECK(cab.TractionMode == traction_mode::catenary); + CHECK(cab.TractionMode() == traction_mode::catenary); } TEST_CASE("genset: the keys reach the vehicle") { @@ -157,7 +157,7 @@ TEST_CASE("genset: the keys reach the vehicle") { 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); + 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); @@ -185,7 +185,7 @@ TEST_CASE("genset: the keys are ignored on other than induction motor vehicles") 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); + CHECK(other->TractionMode() == traction_mode::catenary); } } @@ -195,7 +195,7 @@ TEST_CASE("genset: the selector moves only with the line breaker open") { REQUIRE(test::start_up(test::driving(dragon6), wire)); REQUIRE(cab.lineBreaker.IsClosed()); CHECK_FALSE(cab.TractionModeSwitch(traction_mode::genset)); - CHECK(cab.TractionMode == traction_mode::catenary); + CHECK(cab.TractionMode() == traction_mode::catenary); run(dragon6, 2.0, wire); CHECK(cab.lineBreaker.IsClosed()); cab.MainSwitch(false); @@ -203,7 +203,7 @@ TEST_CASE("genset: the selector moves only with the line breaker open") { CHECK(cab.TractionModeSwitch(traction_mode::genset)); CHECK(cab.GensetSelected()); CHECK(cab.TractionModeSwitch(traction_mode::catenary)); - CHECK(cab.TractionMode == traction_mode::catenary); + CHECK(cab.TractionMode() == traction_mode::catenary); } TEST_CASE("genset: started, it closes the line breaker without a catenary") { @@ -245,7 +245,7 @@ TEST_CASE("genset: on the catenary position the genset feeds nothing") { cab.GensetSwitch(true); run(dragon6, 20.0); REQUIRE(cab.Genset.is_active); - CHECK(cab.TractionMode == traction_mode::catenary); + CHECK(cab.TractionMode() == traction_mode::catenary); CHECK_FALSE(cab.MainSwitchCheck()); close_line_breaker(cab); CHECK_FALSE(cab.lineBreaker.IsClosed()); diff --git a/tests/unit/test_handover.cpp b/tests/unit/test_handover.cpp index ec43a2b3a..ed06f3461 100644 --- a/tests/unit/test_handover.cpp +++ b/tests/unit/test_handover.cpp @@ -62,11 +62,11 @@ TEST_CASE("handover: sanding the player or the automatic system asked for goes o TEST_CASE("handover: the departure signal the AI was giving stops") { auto cab{cab_vehicle()}; cab->signal_departure(true); - REQUIRE(cab->DepartureSignal); + REQUIRE(cab->DepartureSignal()); handover::release_ai_controls(cab.physics(), cab.physics()); - CHECK_FALSE(cab->DepartureSignal); + CHECK_FALSE(cab->DepartureSignal()); } TEST_CASE("handover: the brake releaser the AI was holding lets go") { @@ -86,7 +86,7 @@ TEST_CASE("handover: nothing the AI didn't latch changes") { CHECK(cab->WarningSignal() == 0); CHECK_FALSE(cab->SandDose()); - CHECK_FALSE(cab->DepartureSignal); + CHECK_FALSE(cab->DepartureSignal()); CHECK_FALSE(cab->brakes.distributor->Releaser()); } diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp index 3c8748795..8a8388aae 100644 --- a/tests/unit/test_pullee.cpp +++ b/tests/unit/test_pullee.cpp @@ -89,7 +89,7 @@ TEST_CASE("pullee: a dead Vectron vents the brake pipe of the train hauling it, CHECK(train.hauled->brakes.emergencyValve.flow == 0.0); CHECK(train.locomotive->brakePipe.Pressure() > 4.99); CHECK(train.hauled->brakes.cylinderPressure < 0.1); - CHECK(train.hauled->Fb < 1.0); + CHECK(train.hauled->Fb() < 1.0); CHECK(train.hauled.speed() > 40.0); // running resistance alone } } @@ -154,11 +154,11 @@ TEST_CASE("pullee: the spring brake of a dead locomotive without air stops the t // no air came from anywhere: the cylinder of the spring brake is empty either way REQUIRE(hauled.brakes.spring.pressure < 0.1); if (pullee) { - CHECK(hauled.Fb < 1.0); + CHECK(hauled.Fb() < 1.0); CHECK(train.hauled.speed() > 45.0); } else { - CHECK(hauled.Fb > 30000.0); + CHECK(hauled.Fb() > 30000.0); CHECK(std::abs(train.hauled.speed()) < 1.0); } } @@ -178,14 +178,14 @@ TEST_CASE("pullee: a dead EU47 starts to drag once its main reservoir has leaked train.run(180.0); // charged and released: nothing holds it yet CHECK(hauled.brakes.cylinderPressure < 0.1); - CHECK(hauled.Fb < 1.0); + CHECK(hauled.Fb() < 1.0); train.run(1020.0); // 20 minutes since the start CHECK(hauled.mainPipe.Pressure() < hauled.brakes.spring.minForcePressure); if (pullee) { - CHECK(hauled.Fb < 1.0); + CHECK(hauled.Fb() < 1.0); } else { - CHECK(hauled.Fb > 5000.0); + CHECK(hauled.Fb() > 5000.0); } } } @@ -209,11 +209,11 @@ TEST_CASE("pullee: a vehicle prepared for hauling brakes and releases with the t train.locomotive.hold_brake_pipe(3.5); train.run(20.0); CHECK(hauled.brakes.cylinderPressure > 2.0); - CHECK(hauled.Fb > 30000.0); + CHECK(hauled.Fb() > 30000.0); train.locomotive.hold_brake_pipe(5.0); train.run(90.0); CHECK(hauled.brakes.cylinderPressure < 0.1); - CHECK(hauled.Fb < 1.0); + CHECK(hauled.Fb() < 1.0); CHECK(hauled.brakes.emergencyValve.flow == 0.0); } } @@ -420,7 +420,7 @@ TEST_CASE("pullee: every real vehicle prepared for hauling runs free behind a lo train.run(60.0); CHECK(hauled.brakes.emergencyValve.flow == 0.0); CHECK(hauled.brakes.cylinderPressure < 0.1); - CHECK(hauled.Fb < 1.0); + CHECK(hauled.Fb() < 1.0); CHECK(train.locomotive->brakePipe.Pressure() > 4.99); CHECK(train.hauled.speed() > 40.0); } @@ -444,6 +444,6 @@ TEST_CASE("pullee: every real vehicle standing braked releases once prepared for CHECK(hauled.brakes.emergencyValve.flow == 0.0); CHECK(hauled.brakes.cylinderPressure < 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); + CHECK(hauled.Fb() < 500.0); } } diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp index b982edce5..ec7ef7a13 100644 --- a/vehicle/ai/consist.cpp +++ b/vehicle/ai/consist.cpp @@ -731,7 +731,7 @@ TController::determine_consist_state() { isbraking || bp > 0.4 : // ensure the brakes are sufficiently released when starting to move // once in motion a brake down to 0.4 bar counts as released (UIC), even if its distributor // is still in the lap position while the brake pipe recharges - ( isbraking && bp > 0.4 ) || vehicle->Fb > 10000.0 ) { // 10 kN + ( isbraking && bp > 0.4 ) || vehicle->Fb() > 10000.0 ) { // 10 kN released = false; // ready all the same with the power going on against the brake on purpose: at a standstill, and once // the power holds the train, while the brake releases; otherwise in motion a braking force left diff --git a/vehicle/ai/doors.cpp b/vehicle/ai/doors.cpp index bea5b6d07..2c6855409 100644 --- a/vehicle/ai/doors.cpp +++ b/vehicle/ai/doors.cpp @@ -94,7 +94,7 @@ void TController::Doors( bool const Open, int const Side ) { if (occupied->Doors.has_warning && !drivingFlags.departureWarned) { - if (!occupied->DepartureSignal) + if (!occupied->DepartureSignal()) { // Not warned yet, not warning yet - start the warning signal. cue_action( driver_hint::departuresignalon ); // załącenie bzyczka diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp index 2f0f80812..2869c2174 100644 --- a/vehicle/ai/force.cpp +++ b/vehicle/ai/force.cpp @@ -278,7 +278,7 @@ bool TController::uphill_brake_top_up() { auto haswagons { false }; for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { if( vehicle->physics->Power < 0.01 ) { - trainbrakeforce += vehicle->physics->Fb; + trainbrakeforce += vehicle->physics->Fb(); haswagons = true; } } @@ -368,7 +368,7 @@ void TController::increase_tractive_force() { // Doors() call can potentially adjust fActionTime if( fActionTime < 0.0 ) { return; } } - if( true == occupied->DepartureSignal ) { + if( true == occupied->DepartureSignal() ) { cue_action( driver_hint::departuresignaloff ); } diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp index 0826b5226..93af2a6f5 100644 --- a/vehicle/ai/physicslog.cpp +++ b/vehicle/ai/physicslog.cpp @@ -71,7 +71,7 @@ std::string TController::physicslog_line() const { << occupied->Couplers[1].CForce << " " << occupied->Ft() << " " << occupied->Ff << " " - << occupied->Fb << " " + << occupied->Fb() << " " << occupied->brakes.cylinderPressure << " " << occupied->brakePipe.Pressure() << " " << mvControlling->Im << " " diff --git a/vehicle/ai/speed.cpp b/vehicle/ai/speed.cpp index 45b3cddc2..eccf943ee 100644 --- a/vehicle/ai/speed.cpp +++ b/vehicle/ai/speed.cpp @@ -93,7 +93,7 @@ double TController::ESMVelocity(bool Main) SCPN += 1; if (mvControlling->RList[MCPN].ScndAct < 255 && mvControlling->ScndCtrlActualPos == 0) SCPN = mvControlling->RList[MCPN].ScndAct; - double FrictionMax = mvControlling->Mass*9.81*mvControlling->Adhesive(mvControlling->RunningTrack.friction)*fFrictionCoeff; + double FrictionMax = mvControlling->Mass()*9.81*mvControlling->Adhesive(mvControlling->RunningTrack.friction)*fFrictionCoeff; double IF = mvControlling->Imax; double MS = 0; double Fmax = 0; diff --git a/vehicle/cab/couplingcommands.cpp b/vehicle/cab/couplingcommands.cpp index 6d4bfe1e9..d7a6822b1 100644 --- a/vehicle/cab/couplingcommands.cpp +++ b/vehicle/cab/couplingcommands.cpp @@ -212,7 +212,7 @@ void TTrain::OnCommand_departureannounce(TTrain *Train, command_data const &Comm if (Command.action == GLFW_PRESS) { // only reacting to press, so the sound can loop uninterrupted - if (false == Train->occupied->DepartureSignal) + if (false == Train->occupied->DepartureSignal()) { // turn on Train->occupied->signal_departure(true); diff --git a/vehicle/cab/doorcommands.cpp b/vehicle/cab/doorcommands.cpp index b5ed6b276..53156786c 100644 --- a/vehicle/cab/doorcommands.cpp +++ b/vehicle/cab/doorcommands.cpp @@ -113,7 +113,7 @@ void TTrain::OnCommand_doortoggleleft(TTrain *Train, command_data const &Command if (true == (Train->ggDoorLeftButton.GetDesiredValue() > 0.5 || Train->ggDoorLeftOnButton.GetDesiredValue() > 0.5)) { // open - if (Train->occupied->Doors.has_autowarning && Train->occupied->DepartureSignal) + if (Train->occupied->Doors.has_autowarning && Train->occupied->DepartureSignal()) { // complete closing the doors if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorLeftOffButton.SubModel == nullptr) @@ -402,7 +402,7 @@ void TTrain::OnCommand_doortoggleright(TTrain *Train, command_data const &Comman if (true == (Train->ggDoorRightButton.GetDesiredValue() > 0.5 || Train->ggDoorRightOnButton.GetDesiredValue() > 0.5)) { // open - if (Train->occupied->Doors.has_autowarning && Train->occupied->DepartureSignal) + if (Train->occupied->Doors.has_autowarning && Train->occupied->DepartureSignal()) { // complete closing the doors if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorRightOffButton.SubModel == nullptr) diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 84f80c4b4..4ef8dffcd 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -939,7 +939,7 @@ void TTrain::updateTrainLamps() btLampkaBlokadaDrzwi.Turn(occupied->Doors.is_locked); } btLampkaDoorLockOff.Turn(false == occupied->Doors.lock_enabled); - btLampkaDepartureSignal.Turn(controlled->DepartureSignal); + btLampkaDepartureSignal.Turn(controlled->DepartureSignal()); btLampkaNapNastHam.Turn(controlled->DirActive != 0 && occupied->EpFuse()); // napiecie na nastawniku hamulcowym // Wylaczanie lampek kierunku gdy jedziemy diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp index 7bb3a9ebb..94786d822 100644 --- a/vehicle/dynamic/sounds.cpp +++ b/vehicle/dynamic/sounds.cpp @@ -490,7 +490,7 @@ void TDynamicObject::renderDepartureSignalSounds() { auto const lowvoltagepower { physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable() }; for( auto &doorspeaker : m_doorspeakers ) { // TBD, TODO: per-location door state triggers? - if( physics->DepartureSignal + if( physics->DepartureSignal() && lowvoltagepower /* || ( ( physics->DoorCloseCtrl = control::autonomous ) @@ -1409,7 +1409,7 @@ TDynamicObject::powertrain_sounds::renderTractionMotorSounds( physics::Vehicle c std::clamp( motor_momentum - 1.0 * Deltatime // smooth out decay - + std::abs( Vehicle.Mm ) / 60.0 * Deltatime, + + std::abs( Vehicle.Mm() ) / 60.0 * Deltatime, 0.0, 1.25 ); volume *= std::max( 0.25f, motor_momentum ); motor_volume = std::lerp( motor_volume, volume, 0.25 ); diff --git a/vehicle/handover.cpp b/vehicle/handover.cpp index c232eb155..1e1ab5622 100644 --- a/vehicle/handover.cpp +++ b/vehicle/handover.cpp @@ -21,7 +21,7 @@ void release_ai_controls(physics::Vehicle &Occupied, physics::Vehicle &Controlli if (Controlling.SandDose() && false == (Controlling.SandDoseManual || Controlling.SandDoseAuto)) { Controlling.Sandbox(false); } - if (Occupied.DepartureSignal) { + if (Occupied.DepartureSignal()) { Occupied.signal_departure(false); } if (Occupied.brakes.distributor->Releaser()) { diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index 76ca721d4..60420b5e6 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -226,7 +226,7 @@ void ui::vehicleparams_panel::render_contents() vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabActive : 1) + 0.001f, - physics.Fb * 0.001f, physics.Adhesive(physics.RunningTrack.friction), (physics.SlippingWheels() ? " (!)" : ""), + physics.Fb() * 0.001f, physics.Adhesive(physics.RunningTrack.friction), (physics.SlippingWheels() ? " (!)" : ""), // acceleration physics.AccSVBased(), physics.AccN() + 0.001f, std::string(std::abs(physics.RunningShape.R) > 10000.0 ? "~0" : to_string(physics.RunningShape.R, 0)).c_str(), // velocity From f0978c36c7b085b47507d5e2ae6dd63436f4ae1f Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 13:32:05 +0100 Subject: [PATCH 28/30] refactor(physics): what nothing outside the vehicle uses is private to it 71 public fields of physics::Vehicle that no code outside the class reads or writes (the definitions of the circuits and the tables only the vehicle's own step goes through, the forces and the timers of its step, the programmable controller, ...) move into its private part as they are, with the comments above them. The fields of the old doors inside EU07_USEOLDDOORCODE stay where they are. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- physics/vehicle.h | 151 +++++++++++++++++++++++----------------------- 1 file changed, 76 insertions(+), 75 deletions(-) diff --git a/physics/vehicle.h b/physics/vehicle.h index 89395ab31..1050a3982 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -620,7 +620,6 @@ namespace physics class Vehicle { // Ra: wrapper na kod pascalowy, przejmujący jego funkcje Q: 20160824 - juz nie wrapper a klasa bazowa :) public: - std::string chkPath; bool reload_FIZ(); double const &MoveLength() const { return moveLength; } void SetMoveLength(double const Value) { moveLength = Value; } @@ -637,11 +636,7 @@ class Vehicle } TEngineType EngineType = TEngineType::None; /*typ napedu*/ TPowerParameters EnginePowerSource; /*zrodlo mocy dla silnikow*/ - TPowerParameters SystemPowerSource; /*zrodlo mocy dla systemow sterowania/przetwornic/sprezarek*/ TPowerParameters HeatingPowerSource; /*zrodlo mocy dla ogrzewania*/ - TPowerParameters AlterHeatPowerSource; /*alternatywne zrodlo mocy dla ogrzewania*/ - TPowerParameters LightPowerSource; /*zrodlo mocy dla oswietlenia*/ - TPowerParameters AlterLightPowerSource; /*alternatywne mocy dla oswietlenia*/ double const &Vmax() const { return vmax; } double const &Mass() const { return emptyMass; } double Power = 0.0; /*max. predkosc kontrukcyjna, masa wlasna, moc*/ @@ -661,9 +656,6 @@ class Vehicle 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 const &WheelDiameter() const { return wheelDiameter; } /*srednica kol napednych*/ float WheelDiameterL = 0.9f; // Ra: srednica kol tocznych przednich float WheelDiameterT = 0.9f; // Ra: srednica kol tocznych tylnych @@ -695,13 +687,11 @@ class Vehicle AirSupply air; // the compressor and the main reservoir (physics/components/airsupply.h) Braking brakes; // the blending, the holding brake, the spring brake (physics/components/braking.h) - int UniversalResetButtonFlag[3] = {0, 0, 0}; // customizable reset buttons assignments int TurboTest = 0; /*nastawniki:*/ int MainCtrlPosNo = 0; /*ilosc pozycji nastawnika*/ int const &ScndCtrlPosNo() const { return scndCtrlPosNo; } int LightsPosNo = 0; - int LightsDefPos = 1; bool LightsWrap = false; ByEnd> Lights; // pozycje świateł, przód - tył, 1 .. 16 (17 do lightsset) // the cab interior light each light preset sets, from the optional third column of LightsList (bits of @@ -711,7 +701,6 @@ class Vehicle positions.fill(-1); return positions; }()}; - int ScndInMain{0}; /*zaleznosc bocznika od nastawnika*/ double maxTachoSpeed = {0.0}; // maksymalna predkosc na tarczce predkosciomierza analogowego bool HideDirStatusWhenMoving{false}; // Czy gasic lampki kierunku powyzej predkosci zdefiniowanej przez HideDirStatusSpeed int HideDirStatusSpeed{1}; // Predkosc od ktorej lampki kierunku sa wylaczane @@ -724,11 +713,8 @@ class Vehicle // main reservoir pressure [bar, as MinCP and MaxCP] below which a pneumatic horn stays silent static constexpr double HornMinPressure{2.0}; TUniversalCtrlTable UniCtrlList; /*lista pozycji uniwersalnego nastawnika*/ - int UniCtrlListSize = 0; /*wielkosc listy pozycji uniwersalnego nastawnika*/ - bool UniCtrlIntegratedBrakePNCtrl = false; /*zintegrowany nastawnik JH obsluguje hamulec PN*/ bool UniCtrlIntegratedBrakeCtrl = false; /*zintegrowany nastawnik JH obsluguje hamowanie*/ bool const &UniCtrlIntegratedLocalBrakeCtrl() const { return uniCtrlIntegratedLocalBrakeCtrl; } /*zintegrowany nastawnik JH obsluguje hamowanie hamulcem pomocniczym*/ - int UniCtrlNoPowerPos{0}; // cached highesr position not generating traction force // UCList CtrlValStep: the universal controller (EIMCtrlType 3) changes its setting in steps of this size (e.g. 0.05 for the // 5% steps of the 6Dg), one at once when moved to a raising or lowering position, then one each time its SpeedUp / SpeedDown // covers a step; 0 (the default) changes it continuously @@ -756,7 +742,6 @@ class Vehicle // end; double NominalVoltage = 0.0; /*nominalne napiecie silnika*/ double const &WindingRes() const { return windingRes; } - double u = 0.0; // wspolczynnik tarcia yB wywalic!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! double CircuitRes = 0.0; /*rezystancje silnika i obwodu*/ int IminLo = 0; int IminHi = 0; /*prady przelacznika automatycznego rozruchu, uzywane tez przez ai_driver*/ @@ -767,7 +752,6 @@ class Vehicle double const &InitialCtrlDelay() const { return initialCtrlDelay; } double CtrlDelay = 0.0; /* -//- -//- miedzy kolejnymi poz.*/ double CtrlDownDelay = 0.0; /* -//- -//- przy schodzeniu z poz.*/ /*hunter-101012*/ - int FastSerialCircuit = 0; /*0 - po kolei zamyka styczniki az do osiagniecia szeregowej, 1 - natychmiastowe wejscie na szeregowa*/ /*hunter-111012*/ int BackwardsBranchesAllowed = 1; int const &AutoRelayType() const { return autoRelayType; } /*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 @@ -798,57 +782,28 @@ class Vehicle double force{0.0}; // [N] the braking force, against the motion }; diesel_electric_dynamic_brake DEDynamicBrake; - double TUHEX_Sum = 750; /*nastawa sterownika hamowania ED - aktualna*/ - double TUHEX_Diff = 10; /*histereza działania sterownika hamowania ED*/ - double TUHEX_MinIw = 60; /*minimalny prąd wzbudzenia przy hamowaniu ED - wynika z chk silnika*/ - double TUHEX_MaxIw = 400; /*maksymalny prąd wzbudzenia przy hamowaniu ED - ograniczenie max siły*/ - double TUHEX_Sum1 = 750; /*nastawa1 sterownika hamowania ED*/ - double TUHEX_Sum2 = 750; /*nastawa2 sterownika hamowania ED*/ - double TUHEX_Sum3 = 750; /*nastawa3 sterownika hamowania ED*/ - int TUHEX_Stages = 0; /*liczba stopni hamowania ED*/ - // TODO: wrap resistor fans variables and state into a device - int RVentType = 0; /*0 - brak, 1 - jest, 2 - automatycznie wlaczany*/ double RVentnmax = 1.0; /*maks. obroty wentylatorow oporow rozruchowych*/ - double RVentCutOff = 0.0; /*rezystancja wylaczania wentylatorow dla RVentType=2*/ double RVentSpeed{0.5}; // rozpedzanie sie wentylatora obr/s^2} - double RVentMinI{50.0}; // przy jakim pradzie sie wylaczaja} bool const &RVentForceOn() const { return rventForceOn; } // forced activation switch void SetRVentForceOn(bool const Value) { rventForceOn = Value; } - bool Trafo = false; /*pojazd wyposażony w transformator*/ // the diesel engine, its torque converter and its retarder (physics/components/dieselengine.h) DieselEngine diesel; TorqueConverter torqueConverter; Retarder retarder; - double engagedownspeed = 0.9; - double engageupspeed = 0.5; /*- dla lokomotyw spalinowo-elektrycznych -*/ double const &AnPos() const { return anPos; } // pozycja sterowania dokladnego (analogowego) void SetAnPos(double const Value) { anPos = Value; } - bool AnalogCtrl = false; // - bool AnMainCtrl = false; // bool ShuntModeAllow = false; bool ShuntMode = false; - bool Flat = false; - double Vhyp = 1.0; TDESchemeTable DElist; - TFFSchemeTable FFlist; - int FFListSize = 0; - TFFSchemeTable FFEDlist; - int FFEDListSize = 0; TWiperSchemeTable WiperList; int WiperListSize; - int WiperDefaultPos{0}; - int modernWpierListSize; double Vadd = 1.0; - TMPTRelayTable MPTRelay; int RelayType = 0; - TShuntSchemeTable SST; - double PowerCorRatio = 1.0; // Wspolczynnik korekcyjny /*- dla uproszczonego modelu silnika (dumb) oraz dla drezyny*/ - double Ftmax = 0.0; /*- dla lokomotyw z silnikami indukcyjnymi -*/ // the drive of induction motors (physics/components/inductionmotor.h) InductionMotor inductionMotor; @@ -893,15 +848,11 @@ class Vehicle bool ScndCtrlResistiveLock{false}; // the shunt controller can't be moved, up or down, while the master controller is at zero or on a resistive position, and drops to 0 when the master controller gets there (ScndCtrlResistiveLock=Yes in Cntrl.) bool const &SpeedCtrl() const { return speedCtrl; } /*czy jest tempomat*/ speed_control SpeedCtrlUnit; /*parametry tempomatu*/ - double SpeedCtrlButtons[10]{30, 40, 50, 60, 70, 80, 90, 100, 110, 120}; /*przyciski prędkości*/ - double SpeedCtrlDelay = 2; /*opoznienie dzialania tempomatu z wybieralna predkoscia*/ double SpeedCtrlValue = 0; /*wybrana predkosc jazdy na tempomacie*/ /*--sekcja zmiennych*/ /*--opis konkretnego egzemplarza taboru*/ TLocation const &Loc() const { return location; } // pozycja pojazdów do wyznaczenia odległości pomiędzy sprzęgami void SetLoc(TLocation const Value) { location = Value; } - TRotation Rot{0.0, 0.0, 0.0}; - glm::vec3 Front{}; std::string Name; /*nazwa wlasna*/ ByEnd Couplers; // urzadzenia zderzno-sprzegowe, polaczenia miedzy wagonami // the physical coupler model covers the vehicle: it's in the player's train or in one the player's train closes in on @@ -949,20 +900,15 @@ class Vehicle accN += Acceleration; } double const &nrot() const { return nrotValue; } // predkosc obrotowa kol (obrotow na sekunde) - double nrot_eps = 0.0; // przyspieszenie kątowe kół (bez kierunku) double const &WheelFlat() const { return wheelFlat; } void SetWheelFlat(double const Value) { wheelFlat = Value; } bool const &TruckHunting() const { return truckHunting; } // enable/disable truck hunting calculation void SetTruckHunting(bool const Value) { truckHunting = Value; } /*! rotacja kol [obr/s]*/ double EnginePower = 0.0; /*! chwilowa moc silnikow*/ - double dL = 0.0; double const &Fb() const { return brakingForce; } double Ff = 0.0; /*przesuniecie, sila hamowania i tarcia*/ - double FTrain = 0.0; double FStand = 0.0; /*! sila pociagowa i oporow ruchu*/ - double FTotal = 0.0; /*! calkowita sila dzialajaca na pojazd*/ - double Ntotal = 0.0; /*!s siła nacisku klockow*/ bool const &SlippingWheels() const { return slippingWheels; } bool const &SandDose() const { return sandDose; } /*! poslizg kol, sypanie piasku*/ bool SandDoseManual = false; /*piaskowanie reczne*/ @@ -990,7 +936,6 @@ class Vehicle bool const &RadioStopFlag() const { return radioStopFlag; } /*hamowanie nagle*/ void SetRadioStopFlag(bool const Value) { radioStopFlag = Value; } int TUHEX_StageActual = 0; /*aktualny stopien tuhexa*/ - bool TUHEX_ResChange = false; /*czy zmiana rezystancji hamowania ED - odwzbudzanie*/ bool TUHEX_Active = false; /*czy hamowanie ED wywołane z zewnątrz*/ // NapUdWsp: integer; double const &ActFlowSpeed() const { return actFlowSpeed; } /*szybkosc stabilizatora*/ @@ -1013,7 +958,6 @@ class Vehicle void SetOffsetTrackV(double const Value) { offsetTrackV = Value; } /*-zmienne dla lokomotyw*/ - bool ReleaserEnabledOnlyAtNoPowerPos{false}; int const &MainCtrlPos() const { return mainCtrlPos; } /*polozenie glownego nastawnika*/ void SetMainCtrlPos(int const Value) { mainCtrlPos = Value; } int const &ScndCtrlPos() const { return scndCtrlPos; } /*polozenie dodatkowego nastawnika*/ @@ -1045,7 +989,6 @@ class Vehicle bool const &InsideConsist() const { return insideConsist; } void SetInsideConsist(bool const Value) { insideConsist = Value; } /*-zmienne dla lokomotywy elektrycznej*/ - TTractionParam RunningTraction; /*parametry sieci trakcyjnej najblizej lokomotywy*/ double enrot = 0.0; // ilosc obrotow silnika double Im = 0.0; // prad silnika /* @@ -1057,9 +1000,6 @@ class Vehicle double TotalCurrent = 0.0; // momenty double const &Mm() const { return motorMoment; } - double Mw = 0.0; - // sily napedne - double Fw = 0.0; double const &Ft() const { return ft; } // Ra: Im jest ujemny, jeśli lok jedzie w stronę sprzęgu 1 // a ujemne powinien być przy odwróconej polaryzacji sieci... @@ -1075,7 +1015,6 @@ class Vehicle double LouvresOpenPressure{5.0}; // main reservoir pressure [bar] at which the pneumatic louvres of the motor fans open (ET22) bool ResistorsFlag = false; /*!o jazda rezystorowa*/ double RventRot = 0.0; /*!s obroty wentylatorow rozruchowych*/ - bool s_CAtestebrake = false; // hunter-091012: zmienna dla testu ca std::array, 4> PowerCircuits; // 24v, 110v, 3x400v and 3000v power circuits, voltage from local sources and current draw pairs /*- zmienne dla lokomotyw z silnikami indukcyjnymi -*/ @@ -1083,23 +1022,16 @@ class Vehicle double const &EimicAnalog() const { return eimicAnalog; } /*pozycja zadajnika analogowa*/ void SetEimicAnalog(double const Value) { eimicAnalog = Value; } double eimic_real = 0; /*faktycznie uzywana pozycja zintegrowanego sterowania jazda i hamowaniem*/ - double eimic_step_progress{0.0}; // the part of the next UniCtrlValStep the controller has covered so far double eim_localbrake = 0; /*nastawa hamowania dodatkowego pneumatycznego lokomotywy*/ int EIMCtrlType = 0; /*rodzaj wariantu zadajnika jazdy*/ bool const &SpeedCtrlTypeTime() const { return speedCtrlTypeTime; } /*czy tempomat sterowany czasowo*/ int SpeedCtrlAutoTurnOffFlag = 0; /*czy tempomat sam się wyłącza*/ - bool EIMCtrlAdditionalZeros = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ bool const &EIMCtrlEmergency() const { return eimCtrlEmergency; } /*czy ma dodatkowe zero jazdy i zero hamowania */ bool const &EIMCtrlMainEmergency() const { return eimCtrlMainEmergency; } /*czy zadajnik typu 2 (Elf) ma pozycje hamowania naglego ponizej swojej pozycji 0*/ - double SpeedCtrlTimer = 0; /*zegar dzialania tempomatu z wybieralna predkoscia*/ double const &eimicSpeedCtrl() const { return eimicSpeedCtrlValue; } /*pozycja sugerowana przez tempomat*/ - double eimicSpeedCtrlIntegral = 0; /*calkowany blad ustawienia predkosci*/ double const &NewSpeed() const { return newSpeed; } /*nowa predkosc do zadania*/ /*-zmienne dla drezyny*/ - double PulseForce = 0.0; /*przylozona sila*/ - double PulseForceTimer = 0.0; - int PulseForceCount = 0; /*dla drezyny, silnika spalinowego i parowego*/ double const &eAngle() const { return eAngleValue; } @@ -1108,7 +1040,6 @@ class Vehicle float const &LoadAmount() const { return loadAmount; } /*masa w T lub ilosc w sztukach - zaladowane*/ void SetLoadAmount(float const Value) { loadAmount = Value; } load_attributes LoadType; - std::string LoadQuantity; // jednostki miary // the exchange of the load: +1 unloading, +2 loading, +4 finished, 0 the model of the load updated int LoadStatus() const { return loadStatus; } // a step of the exchange: so much taken out, or put in up to the capacity, and the mass with it @@ -1151,12 +1082,8 @@ class Vehicle } sleep_brakes; /*ABu: stale dla wyznaczania sil (i nie tylko) po optymalizacji*/ - double FrictConst1 = 0.0; - double FrictConst2s = 0.0; - double FrictConst2d = 0.0; double TotalMassxg = 0.0; /*totalMass*g*/ - int iProblem = 0; // flagi problemów z taborem, aby AI nie musiało porównywać; 0=może jechać // the lights switched on at each end (light::), from which the current they draw is counted ByEnd const &LitLights() const { return litLights; } void SetLitLights(VehicleEnd const End, int const Lights) { litLights[End] = Lights; } @@ -1184,7 +1111,6 @@ class Vehicle int modernDimmerDefaultPosition{0}; // bool modernContainOffPos{true}; bool const &enableModernDimmer() const { return enableModernDimmerValue; } - bool modernDimmerCanCycle{false}; // the given dimmer position brought into the DimmerList, to its first or last entry; 0 for an empty list int clampDimmerPosition(int Position) const; // the entry of the current dimmer position, or a plain one (not off, not dimmed, no high beam) when the @@ -1204,7 +1130,6 @@ class Vehicle double highDimMultiplier{2.5f}; // mnoznik dlugich przyciemnionych double highMultiplier{2.8f}; // mnoznik dlugich - plc::basic_controller m_plc; int const &AIHintPantstate() const { return aiHintPantstate; } // suggested pantograph setup // suggested pantograph setup in shunting (AI: ShuntPantstate=, eu07/maszyna#461), the bits as in Pantstate: 1 front, @@ -1862,6 +1787,82 @@ class Vehicle std::optional LightsPresetCabLight(int Position) const; private: + // the state and the definition no code outside the vehicle uses + std::string chkPath; + TPowerParameters SystemPowerSource; /*zrodlo mocy dla systemow sterowania/przetwornic/sprezarek*/ + TPowerParameters AlterHeatPowerSource; /*alternatywne zrodlo mocy dla ogrzewania*/ + TPowerParameters LightPowerSource; /*zrodlo mocy dla oswietlenia*/ + TPowerParameters AlterLightPowerSource; /*alternatywne mocy dla oswietlenia*/ + // 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; + int UniversalResetButtonFlag[3] = {0, 0, 0}; // customizable reset buttons assignments + int LightsDefPos = 1; + int ScndInMain{0}; /*zaleznosc bocznika od nastawnika*/ + int UniCtrlListSize = 0; /*wielkosc listy pozycji uniwersalnego nastawnika*/ + bool UniCtrlIntegratedBrakePNCtrl = false; /*zintegrowany nastawnik JH obsluguje hamulec PN*/ + int UniCtrlNoPowerPos{0}; // cached highesr position not generating traction force + double u = 0.0; // wspolczynnik tarcia yB wywalic!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + int FastSerialCircuit = 0; /*0 - po kolei zamyka styczniki az do osiagniecia szeregowej, 1 - natychmiastowe wejscie na szeregowa*/ /*hunter-111012*/ + double TUHEX_Sum = 750; /*nastawa sterownika hamowania ED - aktualna*/ + double TUHEX_Diff = 10; /*histereza działania sterownika hamowania ED*/ + double TUHEX_MinIw = 60; /*minimalny prąd wzbudzenia przy hamowaniu ED - wynika z chk silnika*/ + double TUHEX_MaxIw = 400; /*maksymalny prąd wzbudzenia przy hamowaniu ED - ograniczenie max siły*/ + double TUHEX_Sum1 = 750; /*nastawa1 sterownika hamowania ED*/ + double TUHEX_Sum2 = 750; /*nastawa2 sterownika hamowania ED*/ + double TUHEX_Sum3 = 750; /*nastawa3 sterownika hamowania ED*/ + int TUHEX_Stages = 0; /*liczba stopni hamowania ED*/ + // TODO: wrap resistor fans variables and state into a device + int RVentType = 0; /*0 - brak, 1 - jest, 2 - automatycznie wlaczany*/ + double RVentCutOff = 0.0; /*rezystancja wylaczania wentylatorow dla RVentType=2*/ + double RVentMinI{50.0}; // przy jakim pradzie sie wylaczaja} + bool Trafo = false; /*pojazd wyposażony w transformator*/ + double engagedownspeed = 0.9; + double engageupspeed = 0.5; + bool AnalogCtrl = false; // + bool AnMainCtrl = false; // + bool Flat = false; + double Vhyp = 1.0; + TFFSchemeTable FFlist; + int FFListSize = 0; + TFFSchemeTable FFEDlist; + int FFEDListSize = 0; + int WiperDefaultPos{0}; + int modernWpierListSize; + TMPTRelayTable MPTRelay; + TShuntSchemeTable SST; + double PowerCorRatio = 1.0; // Wspolczynnik korekcyjny + double Ftmax = 0.0; + double SpeedCtrlButtons[10]{30, 40, 50, 60, 70, 80, 90, 100, 110, 120}; /*przyciski prędkości*/ + double SpeedCtrlDelay = 2; /*opoznienie dzialania tempomatu z wybieralna predkoscia*/ + TRotation Rot{0.0, 0.0, 0.0}; + glm::vec3 Front{}; + double nrot_eps = 0.0; // przyspieszenie kątowe kół (bez kierunku) + double dL = 0.0; + double FTrain = 0.0; + double FTotal = 0.0; /*! calkowita sila dzialajaca na pojazd*/ + double Ntotal = 0.0; /*!s siła nacisku klockow*/ + bool TUHEX_ResChange = false; /*czy zmiana rezystancji hamowania ED - odwzbudzanie*/ + bool ReleaserEnabledOnlyAtNoPowerPos{false}; + TTractionParam RunningTraction; /*parametry sieci trakcyjnej najblizej lokomotywy*/ + double Mw = 0.0; + // sily napedne + double Fw = 0.0; + bool s_CAtestebrake = false; // hunter-091012: zmienna dla testu ca + double eimic_step_progress{0.0}; // the part of the next UniCtrlValStep the controller has covered so far + bool EIMCtrlAdditionalZeros = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ + double SpeedCtrlTimer = 0; /*zegar dzialania tempomatu z wybieralna predkoscia*/ + double eimicSpeedCtrlIntegral = 0; /*calkowany blad ustawienia predkosci*/ + double PulseForce = 0.0; /*przylozona sila*/ + double PulseForceTimer = 0.0; + int PulseForceCount = 0; + std::string LoadQuantity; // jednostki miary + double FrictConst1 = 0.0; + double FrictConst2s = 0.0; + double FrictConst2d = 0.0; + int iProblem = 0; // flagi problemów z taborem, aby AI nie musiało porównywać; 0=może jechać + bool modernDimmerCanCycle{false}; + plc::basic_controller m_plc; // what the vehicle works out or is defined with, which the rest of the simulator only reads double vmax = -1.0; train_type trainType{train_type::generic}; From 23b695752a97e559d339fbfa54cf9b19a6b9c19d Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 13:39:07 +0100 Subject: [PATCH 29/30] refactor(physics): the demand of the integrated controller is private to the vehicle eimic_real, the demand of the integrated controller the vehicle goes by with the speed control counted, which TDynamicObject and the consist braking set for the vehicle that leads, is private: EimicReal() and SetEimicReal(). The field of the same name of drivingaid::input stays as it is. No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit. --- application/driverhints.cpp | 2 +- application/driveruipanels.cpp | 2 +- physics/components/cab.cpp | 2 +- physics/components/commands.cpp | 2 +- physics/components/diesel.cpp | 28 ++++++++++++------------ physics/components/pneumatics.cpp | 2 +- physics/components/traction.cpp | 2 +- physics/consistbraking.cpp | 2 +- physics/vehicle.h | 5 ++++- tests/unit/test_6dg_power_steps.cpp | 6 ++--- tests/unit/test_commands.cpp | 2 +- tests/unit/test_crew.cpp | 4 ++-- tests/unit/test_diesel.cpp | 6 ++--- tests/unit/test_drivingaid.cpp | 16 +++++++------- tests/unit/test_dynamic_brake_diesel.cpp | 12 +++++----- tests/unit/test_elf_controller.cpp | 26 +++++++++++----------- tests/unit/test_speed_control.cpp | 12 +++++----- tests/unit/vehicle.cpp | 4 ++-- vehicle/ai/controls.cpp | 4 ++-- vehicle/cab/update.cpp | 2 +- vehicle/crew.cpp | 2 +- vehicle/drivingaid.cpp | 2 +- vehicle/dynamic/update.cpp | 4 ++-- 23 files changed, 76 insertions(+), 73 deletions(-) diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 0f9c90269..6c00c66f0 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -594,7 +594,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) Action, [this](float const /*Parameter*/) { return AccDesired <= EU07_AI_NOACCELERATION || (false == Ready && false == occupied->ShuntMode) || AccDesired - AbsAccS <= 0.05 || - (occupied->EIMCtrlType > 0 ? mvControlling->eimic_real >= 1.0 : mvControlling->IsScndCtrlMaxPowerPos() && mvControlling->IsMainCtrlMaxPowerPos()); } ); + (occupied->EIMCtrlType > 0 ? mvControlling->EimicReal() >= 1.0 : mvControlling->IsScndCtrlMaxPowerPos() && mvControlling->IsMainCtrlMaxPowerPos()); } ); break; } case driver_hint::bufferscompress: { diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 3f6c18f59..ede3f887e 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -1255,7 +1255,7 @@ debug_panel::update_section_ai( std::vector &Output ) const { "-" ) + ")" + "\n desired diesel percentage: " + std::to_string(mechanik.DizelPercentage) + "/" + std::to_string(mechanik.DizelPercentage_Speed) - + "/" + to_string(100.4*mechanik.mvControlling->eimic_real, 0); + + "/" + to_string(100.4*mechanik.mvControlling->EimicReal(), 0); Output.emplace_back( textline, Global.UITextColor ); diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp index c0c9c0a66..b17bd8624 100644 --- a/physics/components/cab.cpp +++ b/physics/components/cab.cpp @@ -243,7 +243,7 @@ bool physics::Vehicle::EIMDirectionChangeAllow(void) const bool OK = false; /* // NOTE: disabled while eimic variables aren't immediately synced with master controller changes inside ai module - OK = (EngineType != TEngineType::ElectricInductionMotor || ((eimic <= 0) && (eimic_real <= 0) && (Vel < 0.1))); + OK = (EngineType != TEngineType::ElectricInductionMotor || ((eimic <= 0) && (eimicReal <= 0) && (Vel < 0.1))); */ OK = mainCtrlPos <= mainCtrlMaxDirChangePos; return OK; diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp index 49914bdfe..5aed38a8a 100644 --- a/physics/components/commands.cpp +++ b/physics/components/commands.cpp @@ -172,7 +172,7 @@ bool physics::Vehicle::RunControllerCommand(VehicleCommand const Command, double end */ else if (Command == VehicleCommand::integratedController) // ElectricInductionMotor Integrated Control - propulsion and brakes in relative values { - eimic_real = CValue1; + eimicReal = CValue1; OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else diff --git a/physics/components/diesel.cpp b/physics/components/diesel.cpp index b96e2a9dc..8d0909ce5 100644 --- a/physics/components/diesel.cpp +++ b/physics/components/diesel.cpp @@ -337,7 +337,7 @@ double physics::Vehicle::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; + tmp = (DElist[0].RPM + (DElist[MainCtrlPosNo].RPM - DElist[0].RPM) * std::max(0.0, eimicReal)) / 60.0; else tmp = DElist[protection.PressureSwitchTripped() ? MainCtrlNoPowerPos() : mainCtrlPos].RPM / 60.0; @@ -467,7 +467,7 @@ void physics::Vehicle::DieselElectricShuntForce(double const tmpV, double &tmp) // voltage and current limits too. returns the power the generator gives double physics::Vehicle::DieselElectricDigitalForce(double const tmpV, double &tempUmax, double &tempImax) { - auto eimic_positive = std::max(0.0, eimic_real); + auto eimic_positive = std::max(0.0, eimicReal); auto const rpmratio{EngineRPMRatio()}; tempImax = DElist[MainCtrlPosNo].Imax * eimic_positive; tempUmax = DElist[MainCtrlPosNo].Umax * std::min(eimic_positive, rpmratio); @@ -527,7 +527,7 @@ void physics::Vehicle::DieselElectricGenerator(double const tmp, double const te } else { - auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimic_real) : mainCtrlPos; + auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimicReal) : 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); @@ -570,7 +570,7 @@ double physics::Vehicle::dieselelectric_dynamic_brake_demand() const switch (DEDynamicBrake.source) { case diesel_electric_dynamic_brake::control::controller: - return std::clamp(-eimic_real, 0.0, 1.0); + return std::clamp(-eimicReal, 0.0, 1.0); case diesel_electric_dynamic_brake::control::lever: return DynamicBrakeRatio(); default: @@ -608,7 +608,7 @@ double physics::Vehicle::dieselelectric_dynamic_brake_limit() const void physics::Vehicle::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()}; + auto const nopower{brake.source == diesel_electric_dynamic_brake::control::controller ? eimicReal <= 0.0 : IsMainCtrlNoPowerPos()}; if (lineBreaker.IsClosed() && DirActive != 0 && false == FuseFlag && false == slippingWheels && nopower) { brake.level += std::clamp(dieselelectric_dynamic_brake_demand() - brake.level, -brake.rate * dt, brake.rate * dt); @@ -700,10 +700,10 @@ bool physics::Vehicle::dizel_AutoGearCheck(void) auto OK{false}; auto const VelUp{(motor_param(ScndCtrlActualPos).mfi0 != 0.0 ? - motor_param(ScndCtrlActualPos).mfi0 + (motor_param(ScndCtrlActualPos).mfi - motor_param(ScndCtrlActualPos).mfi0) * std::max(0.0, eimic_real) : + motor_param(ScndCtrlActualPos).mfi0 + (motor_param(ScndCtrlActualPos).mfi - motor_param(ScndCtrlActualPos).mfi0) * std::max(0.0, eimicReal) : motor_param(ScndCtrlActualPos).mfi)}; - auto const VelDown{(motor_param(ScndCtrlActualPos).fi0 != 0.0 && eimic_real <= 0.0 ? motor_param(ScndCtrlActualPos).fi0 : motor_param(ScndCtrlActualPos).fi)}; + auto const VelDown{(motor_param(ScndCtrlActualPos).fi0 != 0.0 && eimicReal <= 0.0 ? motor_param(ScndCtrlActualPos).fi0 : motor_param(ScndCtrlActualPos).fi)}; if (motor_param(ScndCtrlActualPos).AutoSwitch && lineBreaker.IsClosed()) { @@ -832,7 +832,7 @@ void physics::Vehicle::dizel_ClutchByIntegratedController() { if (diesel.automaticGearShift == 0) { - if ((torqueConverter.present && torqueConverter.fill > 0.01) || eimic_real > 0.005) + if ((torqueConverter.present && torqueConverter.fill > 0.01) || eimicReal > 0.005) dizel_EngageSwitch(1.0); else if (Vel > retarder.engageVelocity && retarder.present && retarder.fill > 0.01) dizel_EngageSwitch(0.5); @@ -984,10 +984,10 @@ double physics::Vehicle::dizel_fillcheck(int mcp, double dt) double physics::Vehicle::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 && !torqueConverter.lockedUp) + realfill = std::max(0.0, std::min(eimicReal, 1 - motor_param(ScndCtrlActualPos).Isat)); + if (eimicReal > 0.005 && !torqueConverter.lockedUp) { - diesel.governorMinRevolutions = std::min(diesel.governorMinRevolutions + 2.5 * dt, diesel.hydraulicMinRevolutions + eimic_real * diesel.hydraulicMinRevolutionsFactor); + diesel.governorMinRevolutions = std::min(diesel.governorMinRevolutions + 2.5 * dt, diesel.hydraulicMinRevolutions + eimicReal * diesel.hydraulicMinRevolutionsFactor); } else { @@ -1012,7 +1012,7 @@ double physics::Vehicle::dizel_GovernorFill(int const mcp, double realfill) cons { auto nreg{0.0}; if (EIMCtrlType > 0) - nreg = eimic_real > 0.005 ? diesel.governorMaxRevolutions : diesel.minRevolutions; + nreg = eimicReal > 0.005 ? diesel.governorMaxRevolutions : diesel.minRevolutions; else nreg = dizel_GovernorRevolutions(mcp, realfill); if (enrot > nreg) // nad predkoscia regulatora zeruj dawke @@ -1202,7 +1202,7 @@ void physics::Vehicle::hydro_TCFillCheck(double dt) if (torqueConverter.present) // jesli przetwornik momentu { // napelnianie przetwornika - bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; + bool IsPower = EIMCtrlType > 0 ? eimicReal > 0.005 : MainCtrlPowerPos() > 0; if (IsPower && lineBreaker.IsClosed() && enrot > diesel.minRevolutions * 0.9) torqueConverter.fill += torqueConverter.fillRateIncrease * dt; // oproznianie przetwornika @@ -1266,7 +1266,7 @@ void physics::Vehicle::hydro_TCTorque() double physics::Vehicle::dizel_MomentumRetarder(double n, double dt) { - double RetarderRequest = lineBreaker.IsClosed() ? std::max(0.0, -eimic_real) : 0; + double RetarderRequest = lineBreaker.IsClosed() ? std::max(0.0, -eimicReal) : 0; if (retarder.withIndividual) RetarderRequest = LocalBrakeRatio(); if (Vel < retarder.minVelocity) diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 3103f7911..335616420 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -890,7 +890,7 @@ void physics::Vehicle::UpdateLocalBrakeValve(double dt) double lbpa = brakes.config.independentTraxx ? eim_localbrake : brakes.IndependentPosition(); if (EIMCtrlType > 0 && uniCtrlIntegratedLocalBrakeCtrl) { - lbpa = std::max(0.0, -eimic_real); + lbpa = std::max(0.0, -eimicReal); } if (SpeedCtrlUnit.Parking) { diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp index 9af1ba69a..018539c09 100644 --- a/physics/components/traction.cpp +++ b/physics/components/traction.cpp @@ -1152,7 +1152,7 @@ void physics::Vehicle::InductionMotorBrakeBlending(double const ActiveInverters, } else { - PosRatio = std::max(eimic_real, 0.); + PosRatio = std::max(eimicReal, 0.); inductionMotor.state.forceDemand = PosRatio; if (Flat && inductionMotor.traction.startingForce * inductionMotor.state.fullForce > 0) PosRatio = std::min(PosRatio * inductionMotor.traction.startingForce / inductionMotor.state.fullForce, 1.); diff --git a/physics/consistbraking.cpp b/physics/consistbraking.cpp index 405008128..2f86603cb 100644 --- a/physics/consistbraking.cpp +++ b/physics/consistbraking.cpp @@ -71,7 +71,7 @@ void physics::ConsistBrakeBlending::SetControl(Step &state, Vehicle &Lead, Input Lead.CheckSpeedCtrl(dt1); state.eimic = std::min(Lead.eimic, Lead.eimicSpeedCtrl()); - Lead.eimic_real = state.eimic; + Lead.SetEimicReal(state.eimic); // Elf: full braking at once in the lowest position, and in the emergency brake position below it if (Lead.EIMCtrlType == 2 && Lead.MainCtrlPos() <= Lead.EIMCtrlEmergencyPositions()) state.eimic = -1.0; diff --git a/physics/vehicle.h b/physics/vehicle.h index 1050a3982..1a162d79b 100644 --- a/physics/vehicle.h +++ b/physics/vehicle.h @@ -1021,7 +1021,9 @@ class Vehicle double eimic = 0; /*aktualna pozycja zintegrowanego sterowania jazda i hamowaniem*/ double const &EimicAnalog() const { return eimicAnalog; } /*pozycja zadajnika analogowa*/ void SetEimicAnalog(double const Value) { eimicAnalog = Value; } - double eimic_real = 0; /*faktycznie uzywana pozycja zintegrowanego sterowania jazda i hamowaniem*/ + // the demand of the integrated controller the vehicle goes by, the speed control counted /*faktycznie uzywana pozycja zintegrowanego sterowania jazda i hamowaniem*/ + double const &EimicReal() const { return eimicReal; } + void SetEimicReal(double const Value) { eimicReal = Value; } double eim_localbrake = 0; /*nastawa hamowania dodatkowego pneumatycznego lokomotywy*/ int EIMCtrlType = 0; /*rodzaj wariantu zadajnika jazdy*/ bool const &SpeedCtrlTypeTime() const { return speedCtrlTypeTime; } /*czy tempomat sterowany czasowo*/ @@ -1788,6 +1790,7 @@ class Vehicle private: // the state and the definition no code outside the vehicle uses + double eimicReal = 0; std::string chkPath; TPowerParameters SystemPowerSource; /*zrodlo mocy dla systemow sterowania/przetwornic/sprezarek*/ TPowerParameters AlterHeatPowerSource; /*alternatywne zrodlo mocy dla ogrzewania*/ diff --git a/tests/unit/test_6dg_power_steps.cpp b/tests/unit/test_6dg_power_steps.cpp index 5f3d8ce4e..c3ecc2fb0 100644 --- a/tests/unit/test_6dg_power_steps.cpp +++ b/tests/unit/test_6dg_power_steps.cpp @@ -120,7 +120,7 @@ TEST_CASE("6Dg: the shipped definition sets the controller's power demand in ste 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 + CHECK(loco->EimicReal() == doctest::Approx(loco->eimic)); // the demand reaching the drive changed += std::abs(loco->eimic - before) > 1e-9 ? 1 : 0; } CHECK(changed == steps); @@ -178,9 +178,9 @@ TEST_CASE("6Dg: the diesel-electric drive follows the stepped demand") { loco.step(line); } REQUIRE(loco->eimic == doctest::Approx(0.05 * taps)); - REQUIRE(loco->eimic_real == doctest::Approx(0.05 * taps)); + REQUIRE(loco->EimicReal() == 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())); + readings.emplace_back(loco->EimicReal(), 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 diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index 0206fcf5d..cbef02369 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -29,7 +29,7 @@ std::vector state() { {"MainCtrlPos", [](auto const &M) { return M.MainCtrlPos(); }}, {"ScndCtrlPos", [](auto const &M) { return M.ScndCtrlPos(); }}, {"LastRelayTime", [](auto const &M) { return M.lineContactors.TimeSinceSwitch(); }}, - {"eimic_real", [](auto const &M) { return M.eimic_real; }}, + {"eimic_real", [](auto const &M) { return M.EimicReal(); }}, {"TUHEX_StageActual", [](auto const &M) { return M.TUHEX_StageActual; }}, {"TUHEX_Active", [](auto const &M) { return flag(M.TUHEX_Active); }}, {"DynamicBrakeEMUStatus", [](auto const &M) { return flag(M.brakes.electrodynamic.emuWorking); }}, diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp index 601763617..74edbe7ce 100644 --- a/tests/unit/test_crew.cpp +++ b/tests/unit/test_crew.cpp @@ -286,13 +286,13 @@ TEST_CASE("crew: the power an integrated handle asked for goes when the driver l impuls->CabActivisation(); impuls->SetMainCtrlPos(impuls->MainCtrlPosNo); impuls->eimic = 0.8; - impuls->eimic_real = 0.8; + impuls->SetEimicReal(0.8); crew::secure(impuls.physics(), impuls.physics()); CHECK(impuls->MainCtrlPos() == impuls->MainCtrlNoPowerPos()); CHECK(impuls->eimic == 0.0); - CHECK(impuls->eimic_real == 0.0); + CHECK(impuls->EimicReal() == 0.0); CHECK(impuls->brakes.HandlePosition() == static_cast(impuls->brakes.driverValve->GetPos(bh_EB))); CHECK(impuls->CabOccupied() == 0); } diff --git a/tests/unit/test_diesel.cpp b/tests/unit/test_diesel.cpp index 0f49d27f2..1ca7e9ab5 100644 --- a/tests/unit/test_diesel.cpp +++ b/tests/unit/test_diesel.cpp @@ -93,7 +93,7 @@ TEST_CASE("diesel: the 214M railbus's torque converter, gears and retarder") { scenario.get_going(); scenario.full_power(60.0); CHECK(railbus.MainCtrlPos() == 5); - CHECK(railbus.eimic_real == doctest::Approx(1.0)); + CHECK(railbus.EimicReal() == doctest::Approx(1.0)); CHECK(railbus.torqueConverter.lockedUp); CHECK(railbus.ScndCtrlActualPos == railbus.ScndCtrlPosNo()); struct position { @@ -108,7 +108,7 @@ TEST_CASE("diesel: the 214M railbus's torque converter, gears and retarder") { scenario.act(std::format("position {}", number)); railbus.DecMainCtrl(1); scenario.wait(8.0); - CHECK(railbus.eimic_real == doctest::Approx(eimic)); + CHECK(railbus.EimicReal() == doctest::Approx(eimic)); CHECK((railbus.retarder.fill > 0.99) == retarder); CHECK((railbus.retarder.torque > 1000.0) == retarder); CHECK((railbus.brakes.cylinderPressure > 2.0) == air); @@ -159,7 +159,7 @@ TEST_CASE("diesel: the 214M railbus's speed control, up to the speed of a button railbus.SpeedCtrlButton(2); scenario.wait(5.0); // the retarder does it at this speed, the air isn't needed - CHECK(railbus.eimic_real == doctest::Approx(-1.0)); + CHECK(railbus.EimicReal() == doctest::Approx(-1.0)); CHECK(railbus.retarder.fill == doctest::Approx(1.0)); CHECK(railbus.brakes.cylinderPressure < 0.1); CHECK_FALSE(railbus.SpeedCtrlUnit.BrakeInterventionBraking); diff --git a/tests/unit/test_drivingaid.cpp b/tests/unit/test_drivingaid.cpp index 62c2d2be7..438100981 100644 --- a/tests/unit/test_drivingaid.cpp +++ b/tests/unit/test_drivingaid.cpp @@ -33,9 +33,9 @@ drivingaid::readout read(vehicle &Vehicle, drivingaid::cab_controls const &Cab) // what the panel showed before: the throttle and brakes numbers, and the local brake always drivingaid::readout before(physics::Vehicle const &Physics) { drivingaid::readout result; - result.throttle_first = Physics.EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * Physics.eimic_real)) : Physics.MainCtrlPos(); + result.throttle_first = Physics.EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * Physics.EimicReal())) : Physics.MainCtrlPos(); result.throttle_second = Physics.EIMCtrlType > 0 ? Physics.MainCtrlPos() : Physics.ScndCtrlPos(); - result.brake_first = Physics.UniCtrlIntegratedBrakeCtrl ? std::max(0.0, -100.0 * Physics.eimic_real) : Physics.brakes.HandlePositionSmooth(); + result.brake_first = Physics.UniCtrlIntegratedBrakeCtrl ? std::max(0.0, -100.0 * Physics.EimicReal()) : Physics.brakes.HandlePositionSmooth(); result.local_brake = Physics.brakes.IndependentPosition() * LocalBrakePosNo; return result; } @@ -64,7 +64,7 @@ TEST_CASE("driving aid: the Vectron's ED lever shows as a negative throttle step 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(vectron->EimicReal() == 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 @@ -85,10 +85,10 @@ TEST_CASE("driving aid: the Traxx's ED braking from its master controller") { // B+: the braking demand ramps towards full traxx->SetMainCtrlPos(0); traxx.run(3.0, line); - REQUIRE(traxx->eimic_real < -0.2); + REQUIRE(traxx->EimicReal() < -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)); + CHECK(*braking.ed_percent == std::lround(-100.0 * traxx->EimicReal())); // 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); @@ -108,10 +108,10 @@ TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, // the controller at its lowest braking position: the demand ramps towards full braking elf->SetMainCtrlPos(0); elf.run(2.0, line); - REQUIRE(elf->eimic_real < -0.1); + REQUIRE(elf->EimicReal() < -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.ed_percent == std::lround(-100.0 * elf->EimicReal())); CHECK(braking.throttle_first == 0); CHECK(braking.throttle_second == 0); CHECK_FALSE(braking.show_local_brake); @@ -163,7 +163,7 @@ TEST_CASE("driving aid: every real vehicle with a local brake control shows the 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->SetMainCtrlPos(std::min(mainctrl, real->MainCtrlPosNo)); real->brakes.SetIndependentPosition(localbrake); - real->eimic_real = eimic; + real->SetEimicReal(eimic); auto const now{read(real, lever_cab)}; auto const was{before(real.physics())}; CHECK(now.throttle_first == was.throttle_first); diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp index d8e6b05c1..d936ea5d1 100644 --- a/tests/unit/test_dynamic_brake_diesel.cpp +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -23,7 +23,7 @@ std::vector dynamic_brake() { {"EDLevel", [](auto const &M) { return M.DEDynamicBrake.level; }}, {"EDForce", [](auto const &M) { return M.DEDynamicBrake.force; }}, {"DynamicBrakeFlag", [](auto const &M) { return M.brakes.electrodynamic.on ? 1.0 : 0.0; }}, - {"eimic_real", [](auto const &M) { return M.eimic_real; }}, + {"eimic_real", [](auto const &M) { return M.EimicReal(); }}, {"DynamicBrakeCtrlPos", [](auto const &M) { return M.brakes.electrodynamic.controllerPosition; }}, }; } @@ -84,7 +84,7 @@ TEST_CASE("diesel-electric dynamic brake: none without its definition") { scenario.act("braking range"); controller_to(locomotive, 0); scenario.wait(15.0); - CHECK(locomotive.eimic_real == doctest::Approx(-1.0)); + CHECK(locomotive.EimicReal() == doctest::Approx(-1.0)); CHECK(locomotive.Ft() == doctest::Approx(0.0)); CHECK_FALSE(locomotive.brakes.electrodynamic.on); // coasting: braking with the power of the resistors above, it would lose more than 30 km/h @@ -110,7 +110,7 @@ TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { scenario.act("EB+"); controller_to(locomotive, 0); scenario.wait(10.0); - CHECK(locomotive.eimic_real == doctest::Approx(-1.0)); + CHECK(locomotive.EimicReal() == doctest::Approx(-1.0)); CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); CHECK(locomotive.brakes.electrodynamic.on); REQUIRE(locomotive.Vel > 6.0); @@ -121,16 +121,16 @@ TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { scenario.act("EB- to half"); controller_to(locomotive, 2); - for (int i = 0; i < 20 && locomotive.eimic_real < -0.5; ++i) { + for (int i = 0; i < 20 && locomotive.EimicReal() < -0.5; ++i) { scenario.wait(1.0); } scenario.act("EB"); controller_to(locomotive, 1); scenario.wait(2.0); - auto const held{locomotive.eimic_real}; + auto const held{locomotive.EimicReal()}; CHECK(held == doctest::Approx(-0.5).epsilon(0.35)); scenario.wait(5.0); - CHECK(locomotive.eimic_real == doctest::Approx(held)); + CHECK(locomotive.EimicReal() == doctest::Approx(held)); CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(-held).epsilon(0.01)); scenario.act("EB+ to the stop"); diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index c50bc6eac..f3b9a21c6 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -281,7 +281,7 @@ template double release_time(elf &Unit, double Seconds, Action auto const time{i * step_time}; Act(time); Unit.unit.step(Unit.line); - if (cab.UpdateStopBrakeRelease(cab.eimic_real, step_time)) { + if (cab.UpdateStopBrakeRelease(cab.EimicReal(), step_time)) { return time; } } @@ -339,14 +339,14 @@ template start start_off(elf &Unit, double Seconds, Action Act auto const time{i * step_time}; Act(time); Unit.unit.step(Unit.line); - auto const released{cab.UpdateStopBrakeRelease(cab.eimic_real, step_time)}; + auto const released{cab.UpdateStopBrakeRelease(cab.EimicReal(), 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; + result.demand = cab.EimicReal(); } if (cab.Vel > 0.5 && result.moving < 0.0) { result.moving = time; @@ -397,7 +397,7 @@ TEST_CASE("elf holding brake: the controller held at power") { 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)); + CHECK(unit.cab().EimicReal() == 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}; @@ -405,10 +405,10 @@ TEST_CASE("elf holding brake: the controller held at power") { 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}; + auto const demand{cab.EimicReal()}; // the step the ramp of the demand starts at auto rampstart{release}; - while (cab.eimic_real < 0.0101 && rampstart < 5.0) { + while (cab.EimicReal() < 0.0101 && rampstart < 5.0) { rampstart += step_time; unit.unit.step(unit.line); } @@ -425,10 +425,10 @@ TEST_CASE("elf holding brake: the controller flicked to power once and back to h 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); + MESSAGE("flick: release " << release << " s, demand " << cab.EimicReal()); 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)); + CHECK(cab.EimicReal() == doctest::Approx(0.01).epsilon(0.02)); } TEST_CASE("elf holding brake: a demand dropped to zero before the delay starts the count again") { @@ -439,7 +439,7 @@ TEST_CASE("elf holding brake: a demand dropped to zero before the delay starts t 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); + CHECK(cab.EimicReal() > 0.0); } TEST_CASE("elf holding brake: it comes back when the demand drops to zero at standstill") { @@ -451,8 +451,8 @@ TEST_CASE("elf holding brake: it comes back when the demand drops to zero at sta // 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)); + CHECK(cab.EimicReal() <= 0.0); + CHECK_FALSE(cab.UpdateStopBrakeRelease(cab.EimicReal(), 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)); @@ -529,8 +529,8 @@ TEST_CASE("elf holding brake: the force of the motors at 1% against the holding unit.set_controller(3); unit.wait(5.0); auto const holding{cab.brakes.holding.deceleration * mass}; - MESSAGE("mass " << mass << " kg, holding " << holding << " N, cars with motors " << powered << ", demand " << cab.eimic_real << ", cab car Ft " << cab.Ft() + MESSAGE("mass " << mass << " kg, holding " << holding << " N, cars with motors " << powered << ", demand " << cab.EimicReal() << ", cab car Ft " << cab.Ft() << " N, Fful " << cab.inductionMotor.state.fullForce << " kN, speed " << cab.Vel << " km/h after 5 s"); - CHECK(cab.eimic_real == doctest::Approx(0.01).epsilon(0.02)); + CHECK(cab.EimicReal() == doctest::Approx(0.01).epsilon(0.02)); CHECK(cab.Ft() * powered < 0.1 * holding); } diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp index 516334cbf..5878fb64d 100644 --- a/tests/unit/test_speed_control.cpp +++ b/tests/unit/test_speed_control.cpp @@ -22,7 +22,7 @@ std::vector cruise() { {"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; }}, + {"eimic_real", [](auto const &M) { return M.EimicReal(); }}, }; } @@ -199,7 +199,7 @@ TEST_CASE("speed control: the field shunting of the vehicles with a cruise contr CHECK(loco.Vel > 100.0); CHECK(loco.ScndCtrlPos() == 1); CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); - CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); + CHECK(loco.EimicReal() == doctest::Approx(loco.eimic)); // the driver can't move the shunt CHECK_FALSE(loco.IncScndCtrl(1)); CHECK_FALSE(loco.DecScndCtrl(2)); @@ -224,7 +224,7 @@ TEST_CASE("speed control: the field shunting of the vehicles with a cruise contr CHECK(loco.Vel > 130.0); CHECK(most == 0); CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); - CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); + CHECK(loco.EimicReal() == doctest::Approx(loco.eimic)); // the speed buttons do nothing with the cruise control off loco.SpeedCtrlButton(4); loco.SpeedCtrlInc(); @@ -300,7 +300,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the 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 + CHECK(loco.EimicReal() < loco.eimic); // the cruise control holding the power back scenario.act("two steps up"); loco.SpeedCtrlInc(); @@ -337,7 +337,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the 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 + CHECK(loco.EimicReal() == doctest::Approx(loco.eimic)); // the controller's demand again scenario.check(); } @@ -364,7 +364,7 @@ TEST_CASE("speed control apart: the ST45's cruise control on its own switch, wit 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); + CHECK(loco.EimicReal() <= 0.9 + 1e-9); scenario.act("cruise control off"); CHECK(loco.SpeedCtrlSwitch(false)); // off, its buttons do nothing diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index 796005ddd..8e038d664 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -243,13 +243,13 @@ double vehicle::move(track const &Track, double Dt, TLocation const &Location, d if (physics.SpeedCtrl()) { physics.CheckSpeedCtrl(Dt); } - physics.eimic_real = std::min(physics.eimic, physics.eimicSpeedCtrl()); + physics.SetEimicReal(std::min(physics.eimic, physics.eimicSpeedCtrl())); } if (physics.EngineType == ElectricInductionMotor) { // the share of the electric and pneumatic brake over the train (TDynamicObject's MED) isn't here physics.CheckEIMIC(Dt); physics.CheckSpeedCtrl(Dt); - physics.eimic_real = std::min(physics.eimic, physics.eimicSpeedCtrl()); + physics.SetEimicReal(std::min(physics.eimic, physics.eimicSpeedCtrl())); } } diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp index c996d3846..e532afe60 100644 --- a/vehicle/ai/controls.cpp +++ b/vehicle/ai/controls.cpp @@ -1225,7 +1225,7 @@ void TController::SetTimeControllers() DizelPercentage_Speed = std::min(DizelPercentage, mvControlling->Vel < 0.99 * VelDesired ? 1 : 0); } - auto const DizelActualPercentage { int(100.4 * mvControlling->eimic_real) }; + auto const DizelActualPercentage { int(100.4 * mvControlling->EimicReal()) }; auto const PosInc { mvControlling->MainCtrlPosNo }; auto PosDec { 0 }; @@ -1370,7 +1370,7 @@ void TController::CheckTimeControllers() //5.1. Digital controller in DMUs with hydro if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->EIMCtrlType == 3) { - int DizelActualPercentage = 100.4 * mvControlling->eimic_real; + int DizelActualPercentage = 100.4 * mvControlling->EimicReal(); int NeutralPos = mvControlling->MainCtrlPosNo - 1; //przedostatnia powinna wstrzymywać - hipoteza robocza for (int i = mvControlling->MainCtrlPosNo; i >= 0; i--) if (mvControlling->UniCtrlList[i].SetCtrlVal <= 0 && mvControlling->UniCtrlList[i].SpeedDown < 0.01) //niby zero, ale nie zmniejsza procentów diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp index 4ef8dffcd..93e6f8758 100644 --- a/vehicle/cab/update.cpp +++ b/vehicle/cab/update.cpp @@ -553,7 +553,7 @@ void TTrain::completeUnitStates(int const in) // else // fEIMParams[0][3] = // controlled->inductionMotor.state.forceDemand - occupied->LocalBrakeRatio(); // procent zadany - fEIMParams[0][3] = static_cast(occupied->eimic_real); + fEIMParams[0][3] = static_cast(occupied->EimicReal()); fEIMParams[0][4] = std::max(fEIMParams[0][3], 0.f); fEIMParams[0][5] = -std::min(fEIMParams[0][3], 0.f); fEIMParams[0][1] = static_cast(fEIMParams[0][4] * controlled->inductionMotor.state.fullForce); diff --git a/vehicle/crew.cpp b/vehicle/crew.cpp index a2d87480f..0efda42fb 100644 --- a/vehicle/crew.cpp +++ b/vehicle/crew.cpp @@ -28,7 +28,7 @@ void cut_power(physics::Vehicle &Vehicle) { Vehicle.SetScndCtrlPos(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.SetEimicReal(0.0); Vehicle.SpeedCtrlValue = 0.0; Vehicle.SpeedCtrlUnit.IsActive = false; Vehicle.SendCtrlToNext(VehicleCommand::mainController, Vehicle.MainCtrlPosForCoupled(), Vehicle.CabActive); diff --git a/vehicle/drivingaid.cpp b/vehicle/drivingaid.cpp index 15c68faa0..7105edfda 100644 --- a/vehicle/drivingaid.cpp +++ b/vehicle/drivingaid.cpp @@ -65,7 +65,7 @@ input from_vehicles(physics::Vehicle const &Vehicle, physics::Vehicle const &Con result.eimctrltype = Vehicle.EIMCtrlType; result.splited = Controlling.brakes.electrodynamic.splitFromPneumatic; result.integratedbrake = Vehicle.UniCtrlIntegratedBrakeCtrl; - result.eimic_real = Vehicle.eimic_real; + result.eimic_real = Vehicle.EimicReal(); result.dynamicbrakepos = Controlling.brakes.electrodynamic.controllerPosition; result.dynamicbrakeposno = Controlling.brakes.electrodynamic.controllerPositions; result.mainctrlpos = Controlling.MainCtrlPos(); diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 0cdd900bd..398fe1241 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -311,8 +311,8 @@ void TDynamicObject::updateDriver( double const dt1 ) physics->CheckEIMIC(dt1); if (physics->SpeedCtrl()) physics->CheckSpeedCtrl(dt1); - physics->eimic_real = std::min(physics->eimic,physics->eimicSpeedCtrl()); - physics->SendCtrlToNext(VehicleCommand::integratedController, physics->eimic_real, physics->CabActive); + physics->SetEimicReal(std::min(physics->eimic,physics->eimicSpeedCtrl())); + physics->SendCtrlToNext(VehicleCommand::integratedController, physics->EimicReal(), physics->CabActive); } if( Mechanik->primary() && physics->EngineType == TEngineType::ElectricInductionMotor ) { From f6c573340a2dfa05a03f1dd8fccf473d2e6f1c50 Mon Sep 17 00:00:00 2001 From: Hirek193 Date: Sun, 29 Nov 2026 13:39:08 +0100 Subject: [PATCH 30/30] docs(agents): the state of a vehicle changes outside the physics only through its operations AGENTS.md says that outside physics/ the state of a physics::Vehicle changes only through its operations, its definition aside as the vehicle loads; that a field the rest only reads is private with a query named as the field was, one nothing outside uses private outright, and a new one private from the start; and that the cab and the events read the AI through its queries, the debug and timetable panels alone being its friends. --- AGENTS.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 8b7f97f8d..29ce734ed 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -126,6 +126,12 @@ couplers, collisions, derailment) and `vehicle/` (the vehicle in the scenery, th than a `physics::Vehicle &`. The vehicle decides when a part acts and follows up what a step of it reports. A test that sets a state directly uses the `...ForTest()` operation of the part, never a back door in the game's code. A new part follows the same pattern, and a part being worked on moves to it. +- Outside `physics/` the state of a `physics::Vehicle` is changed only through its operations (`SetMainCtrlPos()`, + `SetLitLights()`, `UnloadStep()`, `ShakeVertically()`, ...), never by writing its fields; the only exception is its definition, + which the scenery and the `.mmd` adjust as the vehicle loads. A field the rest of the simulator only reads is private with a + query named as the field was (`Vmax()`, `Ft()`), a field nothing outside uses is private outright, and a new field starts + private. The same holds for `TController`: the cab and the events read it through its queries; only the debug and timetable + panels are its friends. - What concerns a consist rather than a vehicle works on the vehicles of the consist given to it in their order (`physics::ConsistBrakeBlending`), not on `TDynamicObject`, so that it can be tested without the scenery. - The renderer and the rest of the simulator outside `physics/` and `vehicle/` read a vehicle through `TDynamicObject` (its