diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 131cccf11..ff39d872f 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -14,6 +14,14 @@ on:
permissions: {}
+# A newer push to a pull request makes the run for its older commit pointless, so that run is
+# cancelled (sonar.yml then marks the analysis of the older commit as skipped). A push to master
+# gets a group of its own, its commit, so the runs on master are neither cancelled nor held back
+# by one another.
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.sha }}
+ cancel-in-progress: true
+
jobs:
build:
name: Build under Build Wrapper
@@ -33,8 +41,16 @@ jobs:
with:
python-version: '3.14'
+ # A mirror that stops answering used to hold this step for over an hour.
+ # Time out each download, retry it, and give up on the whole step early.
- name: Install build dependencies
+ timeout-minutes: 15
run: |
+ printf '%s\n' \
+ 'Acquire::Retries "3";' \
+ 'Acquire::http::Timeout "60";' \
+ 'Acquire::https::Timeout "60";' \
+ | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null
sudo apt-get update -y
sudo apt-get install -y \
build-essential \
@@ -102,6 +118,7 @@ jobs:
--exclude='*.o' \
--exclude='*.a' \
--exclude='*.so' \
+ --exclude='*.so.*' \
-C "$GITHUB_WORKSPACE" .
- name: Upload analysis input
diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml
index 406f50990..65d74e36f 100644
--- a/.github/workflows/build_bin.yml
+++ b/.github/workflows/build_bin.yml
@@ -27,9 +27,31 @@ jobs:
# Windows / MSVC
# ============================================================
+ # A newer push to the same branch or pull request cancels the build of the older commit. The
+ # groups are set on the build jobs rather than on the workflow, so a publish job that is already
+ # running is left to finish; with a build cancelled the publish job of that run is skipped. A push
+ # to master gets a group of its own, its commit, so the builds of master are never cancelled.
+
+ # Windows is built twice: with AVX2 (the default of ENABLE_AVX2) and without it, for CPUs older
+ # than Haswell (2013). Each variant has its own concurrency group, or one would cancel the other.
+
windows:
- name: Windows x64 / MSVC
+ name: Windows x64 / MSVC / ${{ matrix.variant.name }}
runs-on: windows-2022
+ concurrency:
+ group: ${{ github.workflow }}-windows-${{ matrix.variant.suffix }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }}
+ cancel-in-progress: true
+
+ strategy:
+ fail-fast: false
+ matrix:
+ variant:
+ - name: "AVX2"
+ suffix: "avx2"
+ cmake_flags: "-DENABLE_AVX2=ON"
+ - name: "No AVX2"
+ suffix: "noavx2"
+ cmake_flags: "-DENABLE_AVX2=OFF"
steps:
- name: Checkout repository
@@ -76,6 +98,27 @@ jobs:
run: |
call setup.bat
+ # the unit tests run at the end of the build and load lua51.dll (the Lua screens), but ref/luajit has only its import
+ # library. LuaJIT of the same 2.0 line is built here and put on PATH for them; it doesn't go into the uploaded build
+ - name: Build lua51.dll for the unit tests
+ shell: cmd
+ run: |
+ for /f "usebackq delims=" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "VSDIR=%%i"
+ call "%VSDIR%\VC\Auxiliary\Build\vcvars64.bat" || exit /b 1
+ git init -q "%RUNNER_TEMP%\LuaJIT" || exit /b 1
+ cd /d "%RUNNER_TEMP%\LuaJIT"
+ rem the v2.0 branch of LuaJIT, pinned
+ git fetch -q --depth 1 https://github.com/LuaJIT/LuaJIT.git b83bcba6ea300d4eb16e8257ddf80bcdef1f938b || exit /b 1
+ git checkout -q FETCH_HEAD || exit /b 1
+ cd src
+ rem msvcbuild.bat runs the tools it builds (minilua, buildvm) from the current folder
+ set NoDefaultCurrentDirectoryInExePath=
+ call .\msvcbuild.bat || exit /b 1
+ if not exist lua51.dll exit /b 1
+ mkdir "%RUNNER_TEMP%\lua51"
+ copy /y lua51.dll "%RUNNER_TEMP%\lua51\" || exit /b 1
+ echo %RUNNER_TEMP%\lua51>> "%GITHUB_PATH%"
+
- name: Configure
shell: pwsh
run: |
@@ -83,11 +126,13 @@ jobs:
$pythonRoot = Split-Path $pythonExe
Write-Host "Python root: $pythonRoot"
+ Write-Host "Extra CMake flags: ${{ matrix.variant.cmake_flags }}"
cmake -S . -B build `
-G "Visual Studio 17 2022" `
-A x64 `
- "-DPython3_ROOT_DIR=$pythonRoot"
+ "-DPython3_ROOT_DIR=$pythonRoot" `
+ ${{ matrix.variant.cmake_flags }}
- name: Build
shell: pwsh
@@ -138,7 +183,7 @@ jobs:
- name: Upload Windows build
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
- name: maszyna-windows-x64-${{ env.CONFIG_WIN }}
+ name: maszyna-windows-x64-${{ matrix.variant.suffix }}-${{ env.CONFIG_WIN }}
path: |
build/bin/${{ env.CONFIG_WIN }}/
if-no-files-found: error
@@ -147,7 +192,7 @@ jobs:
- name: Upload Windows debug symbols
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
- name: maszyna-windows-x64-symbols-${{ env.CONFIG_WIN }}
+ name: maszyna-windows-x64-symbols-${{ matrix.variant.suffix }}-${{ env.CONFIG_WIN }}
path: |
build/pdb/${{ env.CONFIG_WIN }}/*.pdb
build/bin/${{ env.CONFIG_WIN }}/*.map
@@ -160,8 +205,23 @@ jobs:
# ============================================================
linux:
- name: Linux x64 / GCC
+ name: Linux x64 / GCC / ${{ matrix.variant.name }}
runs-on: ubuntu-24.04
+ # 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 }}
+ cancel-in-progress: true
+
+ strategy:
+ fail-fast: false
+ matrix:
+ variant:
+ - name: "AVX2"
+ suffix: "avx2"
+ cmake_flags: "-DENABLE_AVX2=ON"
+ - name: "No AVX2"
+ suffix: "noavx2"
+ cmake_flags: "-DENABLE_AVX2=OFF"
steps:
- name: Checkout repository
@@ -176,12 +236,25 @@ jobs:
with:
python-version: "3.14"
+ # A mirror that stops answering used to hold this step for over an hour.
+ # Time out each download, retry it, and give up on the whole step early.
- name: Install Linux dependencies
+ timeout-minutes: 15
run: |
+ printf '%s\n' \
+ 'Acquire::Retries "3";' \
+ 'Acquire::http::Timeout "60";' \
+ 'Acquire::https::Timeout "60";' \
+ | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null
sudo apt-get update
+ # libasound2-dev, libpulse-dev and libpipewire-0.3-dev: the headers of OpenAL Soft's audio backends (built below).
+ # Without them it builds with OSS only, which modern distributions and the Steam Linux Runtime don't have: no sound.
sudo apt-get install -y \
build-essential \
+ libasound2-dev \
+ libpulse-dev \
+ libpipewire-0.3-dev \
libgl1-mesa-dev \
libglew-dev \
libglfw3-dev \
@@ -190,6 +263,7 @@ jobs:
libluajit-5.1-dev \
libserialport-dev \
libsndfile1-dev \
+ libcurl4-openssl-dev \
xorg-dev \
libxkbcommon-dev \
libwayland-dev \
@@ -207,12 +281,17 @@ jobs:
https://github.com/kcat/openal-soft.git \
/tmp/openal-soft
+ # the backends are loaded with dlopen at run time (ALSOFT_DLOPEN), so the bundled library needs none of them;
+ # REQUIRE makes a missing header fail the build instead of shipping a library without sound
cmake \
-S /tmp/openal-soft \
-B /tmp/openal-soft/build \
-DCMAKE_BUILD_TYPE=Release \
-DALSOFT_EXAMPLES=OFF \
- -DALSOFT_UTILS=OFF
+ -DALSOFT_UTILS=OFF \
+ -DALSOFT_REQUIRE_PIPEWIRE=ON \
+ -DALSOFT_REQUIRE_PULSEAUDIO=ON \
+ -DALSOFT_REQUIRE_ALSA=ON
cmake \
--build /tmp/openal-soft/build \
@@ -239,6 +318,7 @@ jobs:
-DWITH_ZMQ=OFF \
-DWITH_OPENVR=OFF \
-DUSE_LTO=OFF \
+ ${{ matrix.variant.cmake_flags }} \
-DPython3_EXECUTABLE="${{ steps.python.outputs.python-path }}" \
-DCMAKE_CXX_FLAGS="-Wno-attributes -fno-inline-functions-called-once"
@@ -247,7 +327,31 @@ jobs:
cmake \
--build build \
--parallel "$(nproc)"
-
+
+ # the build copies the shared libraries next to the game (CMake_modules/bundle_runtime_libs.cmake) and the
+ # game looks for them there first ($ORIGIN): each one it loads from outside build/bin has to be one of the system
+ - name: Check the bundled libraries
+ run: |
+ GAME="$(find build/bin -maxdepth 1 -type f -name 'eu07*' -perm -u+x | head -n 1)"
+ test -n "$GAME"
+ echo "Game: $GAME"
+ readelf -d "$GAME" | grep -E 'R(UN)?PATH'
+ readelf -d "$GAME" | grep -q 'Library rpath: \[\$ORIGIN\]'
+ cat build/bin/bundled_libs.txt
+ ldd "$GAME"
+ if ldd "$GAME" | grep -q 'not found'; then
+ echo "::error::the game needs a library that is neither bundled nor in the system"
+ exit 1
+ fi
+ while read -r name; do
+ [ -n "$name" ] || continue
+ loaded="$(ldd "$GAME" | awk -v n="$name" '$1 == n { print $3 }')"
+ if [ -z "$loaded" ] || [ "$(realpath "$loaded")" != "$(realpath "build/bin/$name")" ]; then
+ echo "::error::$name is bundled, but the game loads it from '$loaded'"
+ exit 1
+ fi
+ done < build/bin/bundled_libs.txt
+
- name: Prepare Linux Python environment
run: |
PYTHON_ROOT="$(python -c 'import sys; print(sys.base_prefix)')"
@@ -280,7 +384,7 @@ jobs:
- name: Upload Linux build
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
- name: maszyna-linux-x64-${{ env.CONFIG_LINUX }}
+ name: maszyna-linux-x64-${{ matrix.variant.suffix }}-${{ env.CONFIG_LINUX }}
path: |
build/bin/
if-no-files-found: error
@@ -303,29 +407,47 @@ jobs:
cancel-in-progress: false
steps:
- - name: Download Windows build
+ # the AVX2 build keeps the old name of the download, so the links already handed out still work
+ - name: Download Windows build (AVX2)
uses: actions/download-artifact@v4
with:
- name: maszyna-windows-x64-${{ env.CONFIG_WIN }}
+ name: maszyna-windows-x64-avx2-${{ env.CONFIG_WIN }}
path: dist/maszyna-windows-x64
- - name: Download Linux build
+ - name: Download Windows build (no AVX2)
uses: actions/download-artifact@v4
with:
- name: maszyna-linux-x64-${{ env.CONFIG_LINUX }}
+ name: maszyna-windows-x64-noavx2-${{ env.CONFIG_WIN }}
+ path: dist/maszyna-windows-x64-noavx2
+
+ - name: Download Linux build (AVX2)
+ uses: actions/download-artifact@v4
+ with:
+ name: maszyna-linux-x64-avx2-${{ env.CONFIG_LINUX }}
path: dist/maszyna-linux-x64
+ - name: Download Linux build (no AVX2)
+ uses: actions/download-artifact@v4
+ with:
+ name: maszyna-linux-x64-noavx2-${{ env.CONFIG_LINUX }}
+ path: dist/maszyna-linux-x64-noavx2
+
- name: Pack
run: |
cd dist
- find maszyna-linux-x64 -type f -exec sh -c 'file -b "$1" | grep -q "^ELF" && chmod +x "$1"' _ {} \;
- if [ -d maszyna-linux-x64/linuxpython64/bin ]; then
- chmod +x maszyna-linux-x64/linuxpython64/bin/*
- fi
+ # the artifacts lose the executable bit
+ for dir in maszyna-linux-x64 maszyna-linux-x64-noavx2; do
+ find "$dir" -type f -exec sh -c 'file -b "$1" | grep -q "^ELF" && chmod +x "$1"' _ {} \;
+ if [ -d "$dir/linuxpython64/bin" ]; then
+ chmod +x "$dir"/linuxpython64/bin/*
+ fi
+ done
(cd maszyna-windows-x64 && zip -qr9 ../maszyna-windows-x64.zip .)
+ (cd maszyna-windows-x64-noavx2 && zip -qr9 ../maszyna-windows-x64-noavx2.zip .)
tar -czf maszyna-linux-x64.tar.gz -C maszyna-linux-x64 .
+ tar -czf maszyna-linux-x64-noavx2.tar.gz -C maszyna-linux-x64-noavx2 .
ls -la
- name: Publish rolling release of the branch
@@ -345,14 +467,18 @@ jobs:
"" \
"Download without a GitHub account:" \
"- Windows: $base/maszyna-windows-x64.zip" \
+ "- Windows, CPUs without AVX2 (older than Haswell, 2013): $base/maszyna-windows-x64-noavx2.zip" \
"- Linux: $base/maszyna-linux-x64.tar.gz" \
+ "- Linux, CPUs without AVX2: $base/maszyna-linux-x64-noavx2.tar.gz" \
"" \
"Unpack over a MaSzyna installation (the game data isn't included). Build log: $RUN_URL")"
gh release delete "$tag" --yes --cleanup-tag || true
gh release create "$tag" \
dist/maszyna-windows-x64.zip \
+ dist/maszyna-windows-x64-noavx2.zip \
dist/maszyna-linux-x64.tar.gz \
+ dist/maszyna-linux-x64-noavx2.tar.gz \
--target "$SHA" \
--prerelease \
--latest=false \
@@ -361,4 +487,6 @@ jobs:
echo "### Public download" >> "$GITHUB_STEP_SUMMARY"
echo "- Windows: $base/maszyna-windows-x64.zip" >> "$GITHUB_STEP_SUMMARY"
+ echo "- Windows, no AVX2: $base/maszyna-windows-x64-noavx2.zip" >> "$GITHUB_STEP_SUMMARY"
echo "- Linux: $base/maszyna-linux-x64.tar.gz" >> "$GITHUB_STEP_SUMMARY"
+ echo "- Linux, no AVX2: $base/maszyna-linux-x64-noavx2.tar.gz" >> "$GITHUB_STEP_SUMMARY"
diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml
new file mode 100644
index 000000000..d2f00bccd
--- /dev/null
+++ b/.github/workflows/coverage.yml
@@ -0,0 +1,135 @@
+# .github/workflows/coverage.yml
+# UNTRUSTED CONTEXT. This workflow runs fork-authored code.
+# It must never reference `secrets.*`. It only builds, runs the unit tests and
+# uploads a report; nothing here feeds the SonarQube Cloud analysis.
+#
+# Coverage of the game's core library (eu07_core) by the unit tests, measured with
+# gcov on a GCC build: the report goes to the summary of the run and to an artifact.
+# It is not sent to SonarQube Cloud on purpose: the project's quality gate ("Sonar
+# way") fails a pull request whose new code is covered in less than 80%, a condition
+# that isn't evaluated as long as sonar-project.properties excludes every file from
+# coverage. Wiring this report in would turn that condition on.
+
+name: Coverage
+
+on:
+ push:
+ branches:
+ - master
+ pull_request:
+ types: [ opened, reopened, synchronize ]
+
+permissions: {}
+
+# A newer push to a pull request cancels the run for its older commit; a push to master
+# gets a group of its own (its commit), so the runs on master are never cancelled.
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.sha }}
+ cancel-in-progress: true
+
+jobs:
+ coverage:
+ name: Unit test coverage (GCC)
+ runs-on: ubuntu-24.04
+ timeout-minutes: 60
+ permissions:
+ contents: read
+ steps:
+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
+ with:
+ submodules: recursive
+
+ - name: Set up Python 3.14
+ uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
+ with:
+ python-version: '3.14'
+
+ # the same packages as the Build workflow: the game is configured as a whole,
+ # though only the unit tests and the core library they link are built
+ - name: Install build dependencies
+ run: |
+ sudo apt-get update -y
+ sudo apt-get install -y \
+ build-essential \
+ libgl1-mesa-dev libglew-dev libglfw3-dev \
+ libpng-dev libopenal-dev libluajit-5.1-dev \
+ libserialport-dev libsndfile1-dev \
+ xorg-dev libxkbcommon-dev libwayland-dev wayland-protocols
+ python3 -m pip install --no-cache-dir --only-binary :all: gcovr==8.3
+
+ - name: Build current OpenAL Soft
+ run: |
+ git clone --depth 1 --branch 1.24.2 https://github.com/kcat/openal-soft.git /tmp/openal-soft
+ cmake -S /tmp/openal-soft -B /tmp/openal-soft/build \
+ -DCMAKE_BUILD_TYPE=Release -DALSOFT_EXAMPLES=OFF -DALSOFT_UTILS=OFF
+ cmake --build /tmp/openal-soft/build -j"$(nproc)"
+ sudo cmake --install /tmp/openal-soft/build
+ sudo ldconfig
+
+ # see the Build workflow
+ - name: Patch GLM for GCC
+ run: |
+ sed -i 's/GLM_FUNC_QUALIFIER std::string format(const char\* message, \.\.\.)/inline std::string format(const char* message, ...)/' \
+ ref/glm/glm/gtx/string_cast.inl
+ grep -n "std::string format(const char\* message" ref/glm/glm/gtx/string_cast.inl
+
+ # unoptimised, so every line keeps its own code and the counts are those of the source
+ - name: Configure (CMake)
+ run: |
+ cmake -S . -B build \
+ -DCMAKE_BUILD_TYPE=Debug \
+ -DWITH_BETTER_RENDERER=OFF \
+ -DWITH_ZMQ=OFF -DWITH_OPENVR=OFF -DUSE_LTO=OFF \
+ -DCMAKE_CXX_FLAGS="--coverage -O0 -Wno-attributes -fno-inline-functions-called-once" \
+ -DPython3_EXECUTABLE="$(which python3)"
+
+ # the tests alone: the game itself isn't linked, so they aren't run by its build
+ - name: Build the unit tests
+ run: cmake --build build --target eu07_unit_tests -j"$(nproc)"
+
+ - name: Run the unit tests
+ run: ./build/tests/unit/eu07_unit_tests
+
+ # the game's own sources only: no submodules, no vendored code, not the tests themselves.
+ # betterRenderer/ is left out for its thirdparty/yaml-cpp, which every target of the game links and so builds here
+ - name: Coverage report
+ run: |
+ # a failure of gcovr fails the step, though its output goes through tee
+ set -o pipefail
+ mkdir -p coverage-report/html
+ gcovr --root . build \
+ --exclude 'ref/' --exclude 'imgui/' --exclude 'stb/' --exclude 'betterRenderer/' \
+ --exclude 'tests/' --exclude 'build/' \
+ --gcov-ignore-parse-errors=negative_hits.warn_once_per_file \
+ --gcov-ignore-errors=no_working_dir_found \
+ --print-summary \
+ --txt coverage-report/coverage.txt \
+ --html-details coverage-report/html/index.html \
+ --sonarqube coverage-report/coverage-sonarqube.xml \
+ --json-summary-pretty --json-summary coverage-report/coverage-summary.json \
+ | tee coverage-report/summary.txt
+ {
+ echo '## Unit test coverage of the core library'
+ echo
+ echo 'GCC, unoptimised build, `eu07_unit_tests`. Lines run by the tests, per source file of the game the tests compile.'
+ echo
+ echo '```'
+ grep -E '^(lines|functions|branches):' coverage-report/summary.txt
+ echo '```'
+ echo
+ echo 'Per file '
+ echo
+ echo '```'
+ cat coverage-report/coverage.txt
+ echo '```'
+ echo
+ echo ' '
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ - name: Upload the coverage report
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ with:
+ name: unit-test-coverage
+ path: coverage-report
+ retention-days: 14
+ if-no-files-found: error
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 000000000..3b52f36ee
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,172 @@
+# MaSzyna: notes for coding agents
+
+These are the instructions for every coding agent that works in this repository: Claude Code, OpenAI Codex, Gemini CLI and any
+other tool that reads `AGENTS.md`. `CLAUDE.md` and `GEMINI.md` only point to this file, so a rule is added or changed here, never
+there.
+
+## The code builds and works with GCC, not only MSVC
+
+The Linux CI (`.github/workflows/build.yml`) builds with GCC 13 on ubuntu-24.04, through the Sonar build-wrapper, and `sonar.yml`
+analyses that build once it has passed. A change that compiles with MSVC only fails there, and a failed GCC build also leaves Sonar
+without an analysis of the PR. So every change has to compile with GCC, and behave the same with it, as well as with MSVC. The CI
+builds with `-DWITH_BETTER_RENDERER=OFF` and Sonar excludes `betterRenderer/`, so that part is neither built on CI nor analysed.
+
+Where no GCC is at hand, read the new code for what MSVC lets through and GCC doesn't:
+
+- `constexpr` initialised from a floating or class-type constant declared only `const`: make the source `constexpr` too.
+- Standard headers MSVC pulls in through others: include them yourself. For example, `` for `std::views`, ``,
+ ``, ``, ``, `` and ``.
+- `typename` and `this->` where a template needs them.
+- A temporary bound to a non-const reference.
+- Explicit specialisations inside a class.
+- A name a class uses and then declares again in its own body (GCC: "changes meaning").
+- A nested type with default member initialisers used as a default argument inside the class that encloses it.
+- A declaration changed in a header (`const`, parameters) without its definition, or a new member function defined but not declared.
+- `std::ifstream` / `std::ofstream` opened with a `std::wstring`.
+- MSVC-only functions: `_stricmp`, `sprintf_s`, `fopen_s`, `localtime_s` and the like.
+- Designated initialisers out of declaration order.
+- `emplace_back(a, b, c)` with parenthesised aggregate initialisation is fine on GCC 13, but not for `std::array`. There is no brace
+ elision in parentheses, so build a named local instead.
+
+The same behaviour needs portable code. Don't rely on the order arguments are evaluated in, on the signedness of `char`, on the size of
+`wchar_t`, or on `long` being 32 bits.
+
+## SonarCloud: the PR passes the quality gate
+
+SonarCloud (`sonar.yml`, `sonar-project.properties`) analyses each PR. A PR has to pass Sonar's quality gate. The gate rates the new
+code: reliability, security and maintainability have to be A, duplication is at most 3% and the security hotspots are reviewed.
+Any bug or vulnerability on the new code lowers its rating below A, so each one gets fixed (or gets a NOSONAR when it is a false
+positive). Code smells count only together, through the maintainability rating, so a single one rarely fails the gate, but many in a
+large PR can. A hotspot is reviewed by marking it in SonarCloud as safe or fixed, which is the user's step there, not a reason to
+rewrite the code. A remark that doesn't fail the gate doesn't have to be fixed. Leave large restructurings that only answer such a
+remark (splitting a class or a file, rewriting a working algorithm) out of the PR. The analysis runs on the GCC build, so a PR that
+fails to build with GCC gets no analysis at all, and so it doesn't pass the gate.
+
+Fixing a remark must not change what the code does:
+
+- Keep the order of side effects, the conditions and the floating-point results as they were.
+- Text in `STR(...)`, `STR_C(...)` and `_(...)` is looked up in the translations (`lang/*.po`), so it stays byte for byte the same.
+ The same goes for what is written to the log.
+- `// NOSONAR: ` is only for a real false positive, or where a fix would change behaviour. Use it rarely, always with the
+ reason.
+
+To keep the gate passing, write new code so that it doesn't raise the rules that keep coming up:
+
+- **S134** (nesting deeper than 3 `if` / `for` / `while` / `switch` / `try`) and **S3776** (cognitive complexity over 25):
+ - use early `continue` / `return`;
+ - move loop bodies and branches into named helpers, preferably free functions in the anonymous namespace;
+ - group the state of a long algorithm in a small struct with methods.
+
+ Every `else if`, every `&&` / `||` sequence and every nested lambda adds to the complexity.
+- **S1188**: a lambda over 20 lines becomes a named function.
+- **S107**: a function with more than 7 parameters takes a struct.
+- **S3608**: lambdas capture explicitly (`[this, &points]`, not `[&]` or `[=]`). The only exception is `[&]` on a lambda passed
+ straight to a standard algorithm; `[=]` is flagged even there, and so is `[&]` passed to one of our own functions.
+- **S6197** / **S5566**: use the `std::ranges::` algorithm that takes the container rather than a begin/end pair or a hand-written
+ loop.
+- **S6165**: use `std::erase_if` rather than erase-remove.
+- **S6004**: a variable used only by the condition is declared in the `if (init; condition)`.
+- **S3358**: no nested `?:`; use an `if` or a small function.
+- **S1121**: no assignment inside an expression, chained ones included (`a = b = c`).
+- **S1117**: no declaration shadowing a local, a member or an enumerator.
+- **S6003**: `v.emplace_back(a, b, c)` rather than `v.push_back({a, b, c})`. For a `std::array` element, push a named local instead
+ (see the GCC notes above).
+- **S6012**: let class template argument deduction work: `std::vector values{1.0, 2.0}`.
+- **S5945**: `std::array` / `std::vector` / `std::string`, not C arrays.
+- **S1659**: one declaration per statement.
+- **S6009**: `std::string_view` rather than `std::string const &` for a string parameter that is only read.
+- **S6185** / **S6494**: `std::format` rather than concatenation or `snprintf`.
+- **S924**: at most one `break` per loop.
+- **S886**: a `for` whose counter changes in its body becomes a `while`.
+- **S5997**: `std::scoped_lock` rather than `std::lock_guard`.
+- **S6168**: `std::jthread` rather than `std::thread`. A `std::jthread` joins in its destructor where a `std::thread` would
+ terminate, so in existing code switch only where the thread is always joined or detached before it is destroyed.
+- **S6177**: `using enum` where a function names many enumerators.
+- **S5350** / **S995**: `const` on references and pointers that aren't written through.
+- **S5817**: `const` on member functions that change nothing.
+- **S2193**: no `float` loop counters.
+- **S5421**: no non-const globals.
+- **S6179**: `std::lerp` rather than a hand-written interpolation, in new code. In existing code only where it gives the very same
+ result.
+- **S6164**: `std::numbers::pi` rather than a literal, in new code. In existing code only where it gives the very same result.
+
+The project is C++20 (`CMAKE_CXX_STANDARD 20`), so no C++23 library addition is available on any compiler. That rules out
+`std::ranges::to`, `views::zip`, `views::enumerate`, `ranges::contains`, `std::print` and `std::expected`.
+
+## Renderers: the move to OpenGL 4.6 and Vulkan
+
+The renderers on `master` are to be replaced. `feat/gl46-migration` (PR #216, a draft with milestone 27.04, to be merged after the
+26.11 release) replaces the OpenGL 3.3 renderer with an OpenGL 4.6 core one and adds a Vulkan 1.4 renderer beside it. It also
+removes the legacy OpenGL 2.1, the OpenGL ES / ANGLE and the NVRHI (`betterRenderer/`) paths.
+
+- `betterRenderer/` will be removed. Don't put work into it.
+- On that branch, of the `rendering/opengl*` files only `openglcamera.*` and `openglmatrixstack.*` stay. The whole
+ `rendering/opengl33*` family and the rest of the legacy `rendering/opengl*` go, and the new renderers are in
+ `rendering/opengl46/`, `rendering/vulkan14/` and `rendering/common/`. The shared `rendering/renderer.*`, `geometrybank.*`,
+ `particles.*` and the like stay. The shaders move from `shaders/` to `shaders/ogl46/` and `shaders/vk14/`.
+- So a change on `master` to the code that goes away, or to the shaders, may be pointless. Keep it to fixes and to what a feature
+ on `master` needs in order to be drawn at all. For such a change, say in the PR where `feat/gl46-migration` has the counterpart,
+ or that the branch already carries the change.
+
+## Building, testing and running
+
+- The unit tests (`tests/unit`) run at the end of the build, which prints `Unit tests: N/N passed` and fails on any failed case.
+ `-DWITH_TESTS=OFF` builds the game without them.
+- A new feature goes on its own branch from `master`, not on whatever branch is checked out. Say which branch the work lands on
+ before the first edit. A fresh worktree has empty submodules, so it doesn't build until they are filled.
+- The editor runs a script when `EU07_EDITOR_SELFTEST=` is set: one command per line, `#` for comments. The commands are in
+ `application/editormodeselftest*.cpp` (`camera`, `wait`, `select`, `lay`, `screenshot`, `save`, `quit` and many more).
+ - Run it on a copy of the scenery, never on the original, and delete the copy afterwards.
+ - Give every run a timeout and keep an eye on its memory. A loop gone wrong can fill the RAM of the whole machine.
+ - `screenshot` only queues the grab and waits 3 frames; the image is written later on another thread. A click right after it
+ has been seen to lose the selection, so leave a `wait` of about 15 frames after a `screenshot` before clicking.
+- At run time the editor's texts load from `lang/editor_.po` in the game folder (`utilities/translation.cpp`), not from
+ the build. New strings of a branch show in English until that file has them. Without the `fonts` folder Polish letters show as `?`.
+- When a build runs on a copy of the game data made of links to the real folders, turn off whatever writes into the data
+ (`convertmodels 0` in `eu07.ini`), or the run changes the real game folder through the links.
+- A test of code that moves, migrates or deletes files in the user's profile (`%APPDATA%`, `%LOCALAPPDATA%`, caches) gets its own
+ test folder. Never point it at the real profile.
+- A GPU hang (Windows TDR) can freeze the whole machine, not just the game. Don't test a hang hypothesis by running it. Guard the
+ code against what causes it (degenerate geometry, NaN in the camera or in transforms) and read the `LiveKernelEvent` / watchdog
+ dumps instead.
+- PowerShell variable names are case-insensitive: `$Track` and `$track` are the same variable.
+
+## Game data and backward compatibility
+
+The code and the game data live apart. The assets (sceneries, vehicles with their `.fiz` and `.mmd`, models, textures, sounds,
+timetables, most of `lang` and the shipped `eu07.ini`) are in a separate SVN repository, `https://svn.eu07.pl/pctga`. It needs an
+account; there is no anonymous checkout. Of `lang/`, only `editor_pl.po` is in this repository. Players install and
+launch the game through Steam, GOG and the like, and run new builds on the data they already have.
+
+The official starter is StarterNG (`https://github.com/MaSzyna-EU07/StarterNG`), a separate repository; the older
+`MaSzyna-EU07/Starter` is not the one in use. `launcher/` in this repository is the simulator's built-in scenario and vehicle
+picker (`launcher_mode`), not StarterNG.
+
+- Every existing file must still be read the way it was. Don't rename or drop a keyword, change the meaning or the unit of a value,
+ or make an optional entry required. This holds for every format the game reads: for example `.scn` and its includes, `.fiz`,
+ `.mmd`, `.e3d` / `.t3d`, `.mat`, the `.txt` timetables and track profiles, `eu07.ini` and the Python screens.
+- A bug fix may change what an existing file leads to, such as how a vehicle from its `.fiz` behaves, as long as the PR says so.
+- Something new in a format is optional, and without it the code does exactly what it did before. A file that loaded correctly
+ before doesn't get new warnings or errors in the log. A real fault that is newly detected may be logged.
+- A code change must not need a change in the SVN to work. Where it uses new or changed assets, it falls back to the old behaviour
+ without them, and the PR says what is to be added to the SVN and in what order the two go in.
+- A change that uses new or changed assets (and falls back without them, see above) says so plainly in its commit message: which
+ files, and what is to change in them. It is never left implied. Before such a commit, either make the asset change right away in
+ the user's SVN working copy, or get the user's agreement to leave it for later. Ask the user where their SVN working copy is; the
+ installed game folder is not one. Pushing to git and committing to the SVN both need the user's consent.
+- A scenery saved by the editor without using a new feature holds nothing the current release can't read. The entries of a new
+ feature (such as a new kind of node) appear only where that feature was used, and the PR says that the release doesn't read
+ them.
+- Saving patches the scenery files by byte spans: unchanged definitions stay byte for byte, and an edited node is written anew by
+ its `export_as_text`. A change to saving must not widen what gets rewritten, nor make `export_as_text` drop more of an edited
+ node (comments, unknown tokens) than it did before.
+- A new feature that changes what the simulator does or shows with existing sceneries and vehicles can be turned off in
+ `eu07.ini`, and turned off, the simulator behaves as it did before the feature. Editor tools and new optional entries of a
+ format are covered by the points above. The key is parsed in `utilities/Globals.cpp` (`global_settings::ConfigParse*`) and
+ written by `global_settings::export_as_text`, which puts the settings in the log at start. `eu07.ini` is read from the user's
+ profile (`user_config_path`), and from the game folder only when the profile has none; test the switch in the file that is
+ actually read.
+- A feature doesn't make existing sceneries and vehicles look suddenly different after an update. A change to how things look is
+ something the player turns on, or comes in gradually.
+- When a format really has to change, read both the old and the new form, and say in the PR what changes for the data and for
+ the people who make it.
diff --git a/CLAUDE.md b/CLAUDE.md
index 283058cbe..bbbaa3835 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,168 +1,5 @@
# MaSzyna: notes for Claude Code
-## The code builds and works with GCC, not only MSVC
+The instructions for every coding agent in this repository are in `AGENTS.md`. Add or change rules there, not here.
-The Linux CI (`.github/workflows/build.yml`) builds with GCC 13 on ubuntu-24.04, through the Sonar build-wrapper, and `sonar.yml`
-analyses that build once it has passed. A change that compiles with MSVC only fails there, and a failed GCC build also leaves Sonar
-without an analysis of the PR. So every change has to compile with GCC, and behave the same with it, as well as with MSVC. The CI
-builds with `-DWITH_BETTER_RENDERER=OFF` and Sonar excludes `betterRenderer/`, so that part is neither built on CI nor analysed.
-
-Where no GCC is at hand, read the new code for what MSVC lets through and GCC doesn't:
-
-- `constexpr` initialised from a floating or class-type constant declared only `const`: make the source `constexpr` too.
-- Standard headers MSVC pulls in through others: include them yourself. For example, `` for `std::views`, ``,
- ``, ``, ``, `` and ``.
-- `typename` and `this->` where a template needs them.
-- A temporary bound to a non-const reference.
-- Explicit specialisations inside a class.
-- A name a class uses and then declares again in its own body (GCC: "changes meaning").
-- A nested type with default member initialisers used as a default argument inside the class that encloses it.
-- A declaration changed in a header (`const`, parameters) without its definition, or a new member function defined but not declared.
-- `std::ifstream` / `std::ofstream` opened with a `std::wstring`.
-- MSVC-only functions: `_stricmp`, `sprintf_s`, `fopen_s`, `localtime_s` and the like.
-- Designated initialisers out of declaration order.
-- `emplace_back(a, b, c)` with parenthesised aggregate initialisation is fine on GCC 13, but not for `std::array`. There is no brace
- elision in parentheses, so build a named local instead.
-
-The same behaviour needs portable code. Don't rely on the order arguments are evaluated in, on the signedness of `char`, on the size of
-`wchar_t`, or on `long` being 32 bits.
-
-## SonarCloud: the PR passes the quality gate
-
-SonarCloud (`sonar.yml`, `sonar-project.properties`) analyses each PR. A PR has to pass Sonar's quality gate. The gate rates the new
-code: reliability, security and maintainability have to be A, duplication is at most 3% and the security hotspots are reviewed.
-Any bug or vulnerability on the new code lowers its rating below A, so each one gets fixed (or gets a NOSONAR when it is a false
-positive). Code smells count only together, through the maintainability rating, so a single one rarely fails the gate, but many in a
-large PR can. A hotspot is reviewed by marking it in SonarCloud as safe or fixed, which is the user's step there, not a reason to
-rewrite the code. A remark that doesn't fail the gate doesn't have to be fixed. Leave large restructurings that only answer such a
-remark (splitting a class or a file, rewriting a working algorithm) out of the PR. The analysis runs on the GCC build, so a PR that
-fails to build with GCC gets no analysis at all, and so it doesn't pass the gate.
-
-Fixing a remark must not change what the code does:
-
-- Keep the order of side effects, the conditions and the floating-point results as they were.
-- Text in `STR(...)`, `STR_C(...)` and `_(...)` is looked up in the translations (`lang/*.po`), so it stays byte for byte the same.
- The same goes for what is written to the log.
-- `// NOSONAR: ` is only for a real false positive, or where a fix would change behaviour. Use it rarely, always with the
- reason.
-
-To keep the gate passing, write new code so that it doesn't raise the rules that keep coming up:
-
-- **S134** (nesting deeper than 3 `if` / `for` / `while` / `switch` / `try`) and **S3776** (cognitive complexity over 25):
- - use early `continue` / `return`;
- - move loop bodies and branches into named helpers, preferably free functions in the anonymous namespace;
- - group the state of a long algorithm in a small struct with methods.
-
- Every `else if`, every `&&` / `||` sequence and every nested lambda adds to the complexity.
-- **S1188**: a lambda over 20 lines becomes a named function.
-- **S107**: a function with more than 7 parameters takes a struct.
-- **S3608**: lambdas capture explicitly (`[this, &points]`, not `[&]` or `[=]`). The only exception is `[&]` on a lambda passed
- straight to a standard algorithm; `[=]` is flagged even there, and so is `[&]` passed to one of our own functions.
-- **S6197** / **S5566**: use the `std::ranges::` algorithm that takes the container rather than a begin/end pair or a hand-written
- loop.
-- **S6165**: use `std::erase_if` rather than erase-remove.
-- **S6004**: a variable used only by the condition is declared in the `if (init; condition)`.
-- **S3358**: no nested `?:`; use an `if` or a small function.
-- **S1121**: no assignment inside an expression, chained ones included (`a = b = c`).
-- **S1117**: no declaration shadowing a local, a member or an enumerator.
-- **S6003**: `v.emplace_back(a, b, c)` rather than `v.push_back({a, b, c})`. For a `std::array` element, push a named local instead
- (see the GCC notes above).
-- **S6012**: let class template argument deduction work: `std::vector values{1.0, 2.0}`.
-- **S5945**: `std::array` / `std::vector` / `std::string`, not C arrays.
-- **S1659**: one declaration per statement.
-- **S6009**: `std::string_view` rather than `std::string const &` for a string parameter that is only read.
-- **S6185** / **S6494**: `std::format` rather than concatenation or `snprintf`.
-- **S924**: at most one `break` per loop.
-- **S886**: a `for` whose counter changes in its body becomes a `while`.
-- **S5997**: `std::scoped_lock` rather than `std::lock_guard`.
-- **S6168**: `std::jthread` rather than `std::thread`. A `std::jthread` joins in its destructor where a `std::thread` would
- terminate, so in existing code switch only where the thread is always joined or detached before it is destroyed.
-- **S6177**: `using enum` where a function names many enumerators.
-- **S5350** / **S995**: `const` on references and pointers that aren't written through.
-- **S5817**: `const` on member functions that change nothing.
-- **S2193**: no `float` loop counters.
-- **S5421**: no non-const globals.
-- **S6179**: `std::lerp` rather than a hand-written interpolation, in new code. In existing code only where it gives the very same
- result.
-- **S6164**: `std::numbers::pi` rather than a literal, in new code. In existing code only where it gives the very same result.
-
-The project is C++20 (`CMAKE_CXX_STANDARD 20`), so no C++23 library addition is available on any compiler. That rules out
-`std::ranges::to`, `views::zip`, `views::enumerate`, `ranges::contains`, `std::print` and `std::expected`.
-
-## Renderers: the move to OpenGL 4.6 and Vulkan
-
-The renderers on `master` are to be replaced. `feat/gl46-migration` (PR #216, a draft with milestone 27.04, to be merged after the
-26.11 release) replaces the OpenGL 3.3 renderer with an OpenGL 4.6 core one and adds a Vulkan 1.4 renderer beside it. It also
-removes the legacy OpenGL 2.1, the OpenGL ES / ANGLE and the NVRHI (`betterRenderer/`) paths.
-
-- `betterRenderer/` will be removed. Don't put work into it.
-- On that branch, of the `rendering/opengl*` files only `openglcamera.*` and `openglmatrixstack.*` stay. The whole
- `rendering/opengl33*` family and the rest of the legacy `rendering/opengl*` go, and the new renderers are in
- `rendering/opengl46/`, `rendering/vulkan14/` and `rendering/common/`. The shared `rendering/renderer.*`, `geometrybank.*`,
- `particles.*` and the like stay. The shaders move from `shaders/` to `shaders/ogl46/` and `shaders/vk14/`.
-- So a change on `master` to the code that goes away, or to the shaders, may be pointless. Keep it to fixes and to what a feature
- on `master` needs in order to be drawn at all. For such a change, say in the PR where `feat/gl46-migration` has the counterpart,
- or that the branch already carries the change.
-
-## Building, testing and running
-
-- The unit tests (`tests/unit`) run at the end of the build, which prints `Unit tests: N/N passed` and fails on any failed case.
- `-DWITH_TESTS=OFF` builds the game without them.
-- A new feature goes on its own branch from `master`, not on whatever branch is checked out. Say which branch the work lands on
- before the first edit. A fresh worktree has empty submodules, so it doesn't build until they are filled.
-- The editor runs a script when `EU07_EDITOR_SELFTEST=` is set: one command per line, `#` for comments. The commands are in
- `application/editormodeselftest*.cpp` (`camera`, `wait`, `select`, `lay`, `screenshot`, `save`, `quit` and many more).
- - Run it on a copy of the scenery, never on the original, and delete the copy afterwards.
- - Give every run a timeout and keep an eye on its memory. A loop gone wrong can fill the RAM of the whole machine.
- - `screenshot` only queues the grab and waits 3 frames; the image is written later on another thread. A click right after it
- has been seen to lose the selection, so leave a `wait` of about 15 frames after a `screenshot` before clicking.
-- At run time the editor's texts load from `lang/editor_.po` in the game folder (`utilities/translation.cpp`), not from
- the build. New strings of a branch show in English until that file has them. Without the `fonts` folder Polish letters show as `?`.
-- When a build runs on a copy of the game data made of links to the real folders, turn off whatever writes into the data
- (`convertmodels 0` in `eu07.ini`), or the run changes the real game folder through the links.
-- A test of code that moves, migrates or deletes files in the user's profile (`%APPDATA%`, `%LOCALAPPDATA%`, caches) gets its own
- test folder. Never point it at the real profile.
-- A GPU hang (Windows TDR) can freeze the whole machine, not just the game. Don't test a hang hypothesis by running it. Guard the
- code against what causes it (degenerate geometry, NaN in the camera or in transforms) and read the `LiveKernelEvent` / watchdog
- dumps instead.
-- PowerShell variable names are case-insensitive: `$Track` and `$track` are the same variable.
-
-## Game data and backward compatibility
-
-The code and the game data live apart. The assets (sceneries, vehicles with their `.fiz` and `.mmd`, models, textures, sounds,
-timetables, most of `lang` and the shipped `eu07.ini`) are in a separate SVN repository, `https://svn.eu07.pl/pctga`. It needs an
-account; there is no anonymous checkout. Of `lang/`, only `editor_pl.po` is in this repository. Players install and
-launch the game through Steam, GOG and the like, and run new builds on the data they already have.
-
-The official starter is StarterNG (`https://github.com/MaSzyna-EU07/StarterNG`), a separate repository; the older
-`MaSzyna-EU07/Starter` is not the one in use. `launcher/` in this repository is the simulator's built-in scenario and vehicle
-picker (`launcher_mode`), not StarterNG.
-
-- Every existing file must still be read the way it was. Don't rename or drop a keyword, change the meaning or the unit of a value,
- or make an optional entry required. This holds for every format the game reads: for example `.scn` and its includes, `.fiz`,
- `.mmd`, `.e3d` / `.t3d`, `.mat`, the `.txt` timetables and track profiles, `eu07.ini` and the Python screens.
-- A bug fix may change what an existing file leads to, such as how a vehicle from its `.fiz` behaves, as long as the PR says so.
-- Something new in a format is optional, and without it the code does exactly what it did before. A file that loaded correctly
- before doesn't get new warnings or errors in the log. A real fault that is newly detected may be logged.
-- A code change must not need a change in the SVN to work. Where it uses new or changed assets, it falls back to the old behaviour
- without them, and the PR says what is to be added to the SVN and in what order the two go in.
-- A change that uses new or changed assets (and falls back without them, see above) says so plainly in its commit message: which
- files, and what is to change in them. It is never left implied. Before such a commit, either make the asset change right away in
- the user's SVN working copy, or get the user's agreement to leave it for later. Ask the user where their SVN working copy is; the
- installed game folder is not one. Pushing to git and committing to the SVN both need the user's consent.
-- A scenery saved by the editor without using a new feature holds nothing the current release can't read. The entries of a new
- feature (such as a new kind of node) appear only where that feature was used, and the PR says that the release doesn't read
- them.
-- Saving patches the scenery files by byte spans: unchanged definitions stay byte for byte, and an edited node is written anew by
- its `export_as_text`. A change to saving must not widen what gets rewritten, nor make `export_as_text` drop more of an edited
- node (comments, unknown tokens) than it did before.
-- A new feature that changes what the simulator does or shows with existing sceneries and vehicles can be turned off in
- `eu07.ini`, and turned off, the simulator behaves as it did before the feature. Editor tools and new optional entries of a
- format are covered by the points above. The key is parsed in `utilities/Globals.cpp` (`global_settings::ConfigParse*`) and
- written by `global_settings::export_as_text`, which puts the settings in the log at start. `eu07.ini` is read from the user's
- profile (`user_config_path`), and from the game folder only when the profile has none; test the switch in the file that is
- actually read.
-- A feature doesn't make existing sceneries and vehicles look suddenly different after an update. A change to how things look is
- something the player turns on, or comes in gradually.
-- When a format really has to change, read both the old and the new form, and say in the PR what changes for the data and for
- the people who make it.
+@AGENTS.md
diff --git a/CMakeLists.txt b/CMakeLists.txt
index c38285647..9e9b55d86 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -83,6 +83,7 @@ option(WITH_CRASHPAD "Compile with crashpad" OFF)
option(WITH_DISCORD_RPC "Compile with DISCORD RICH PRESENCE" ON)
option(USE_LTO "Use link-time optimization" OFF)
option(WITH_TESTS "Build and run the unit tests with the game, a failing test fails the build" ON)
+option(WITH_EDITOR_SELFTESTS "Run the scripts of the editor and launcher self-tests named by the EU07_EDITOR_SELFTEST and EU07_LAUNCHER_SELFTEST variables" OFF)
option(GENERATE_PDB "Generate executable with program debugging symbols" ON)
option(ENABLE_MCC "Enable multicore compilation" ON)
option(WITHDUMPGEN "Enable generating DMP files on crash" ON)
@@ -189,6 +190,7 @@ set(SOURCES
"scene/scene.cpp"
"scene/scenenode.cpp"
"simulation/simulation.cpp"
+"simulation/blackboxrecorder.cpp"
"model/vertex.cpp"
"audio/audio.cpp"
"audio/audiorenderer.cpp"
@@ -213,6 +215,8 @@ set(SOURCES
"editor/editorIncludeInfo.cpp"
"editor/editorTerrain.cpp"
"editor/editorTrack.cpp"
+"editor/editorTrackTrace.cpp"
+"editor/editorFouling.cpp"
"editor/editorRoad.cpp"
"editor/editorAlignment.cpp"
"editor/editorTrackShape.cpp"
@@ -249,7 +253,9 @@ set(SOURCES
"application/editormoderecords.cpp"
"application/editormodeswitchdrive.cpp"
"application/editormodeswitchtool.cpp"
+"application/editormodeswitchtemplate.cpp"
"application/editormodenmt.cpp"
+"application/editormodegradeline.cpp"
"application/editormodeswitchslide.cpp"
"application/editormodeswitchdesign.cpp"
"application/editormodetrackbed.cpp"
@@ -259,6 +265,8 @@ set(SOURCES
"application/editormodeprofile.cpp"
"application/editormodetextures.cpp"
"application/editormodegauge.cpp"
+"application/editormoderide.cpp"
+"application/editormodeminimap.cpp"
"application/editormodeinfra.cpp"
"application/editormodespeed.cpp"
"application/editormodesrk.cpp"
@@ -634,6 +642,11 @@ if (ADD_VERSION_SUFFIX)
set (SUFFIX "_${SRC_SHORT_DATE}_${GIT_HASH}")
endif()
+# a build without AVX2 says so in its name, so a starter can pick it on a CPU without AVX2
+if (NOT ENABLE_AVX2)
+ set (SUFFIX "${SUFFIX}_noavx2")
+endif()
+
set(OPENVR_LIBRARY "openvr_api")
set(OPENVR_INCLUDE_DIR "")
@@ -695,6 +708,7 @@ set(CORE_SOURCES
"McZapkie/friction.cpp"
"McZapkie/hamulce.cpp"
"McZapkie/Mover.cpp"
+"McZapkie/couplerphysics.cpp"
"McZapkie/Oerlikon_ESt.cpp"
"utilities/parser.cpp"
"utilities/utilities.cpp"
@@ -703,11 +717,15 @@ set(CORE_SOURCES
"scripting/scriptscreenkernels.cpp"
"scripting/scriptscreendrawing.cpp"
"simulation/simulationtestrules.cpp"
+"vehicle/blackbox.cpp"
+"utilities/physicslog.cpp"
"vehicle/enginestart.cpp"
+"vehicle/brakesetting.cpp"
"vehicle/handover.cpp"
"vehicle/horn.cpp"
"vehicle/linebreaker.cpp"
"vehicle/smoke.cpp"
+"vehicle/odometer.cpp"
)
add_library(eu07_core STATIC ${CORE_SOURCES})
target_link_libraries(eu07_core PUBLIC eu07_settings)
@@ -869,6 +887,12 @@ else()
target_compile_definitions(eu07_settings INTERFACE WITH_DISCORD_RPC=0)
endif()
+if(WITH_EDITOR_SELFTESTS)
+ target_compile_definitions(eu07_settings INTERFACE WITH_EDITOR_SELFTESTS=1)
+else()
+ target_compile_definitions(eu07_settings INTERFACE WITH_EDITOR_SELFTESTS=0)
+endif()
+
find_package(OpenAL REQUIRED)
if (TARGET OpenAL::OpenAL)
target_link_libraries(eu07_settings INTERFACE OpenAL::OpenAL)
@@ -899,7 +923,8 @@ if (WIN32)
target_link_libraries(eu07_settings INTERFACE ws2_32)
endif()
-# http client of the editor's geoportal orthophoto layer: WinHTTP on Windows, libcurl elsewhere when available
+# http client of the editor, for the orthophoto, the terrain model and the topo map of geoportal.gov.pl: WinHTTP on Windows,
+# libcurl elsewhere when available
if (WIN32)
target_link_libraries(eu07_settings INTERFACE winhttp)
else()
@@ -908,7 +933,7 @@ else()
target_link_libraries(eu07_settings INTERFACE CURL::libcurl)
target_compile_definitions(eu07_settings INTERFACE EU07_WITH_CURL)
else()
- message(STATUS "libcurl not found: the editor's orthophoto layer will only show cached tiles")
+ message(STATUS "libcurl not found: the editor's orthophoto and terrain model will only show what's cached, its topo map nothing")
endif()
endif()
@@ -925,6 +950,41 @@ if (WIN32)
)
endif ()
+# Linux: the game loads its shared libraries from its own folder first ($ORIGIN), and the build copies them there,
+# so the folder runs on a system that doesn't have them, or has other versions. the RPATH is a DT_RPATH rather
+# than a DT_RUNPATH, because only that one is also used for the libraries the copied ones load (libsndfile's codecs)
+if (UNIX AND NOT APPLE)
+ option(BUNDLE_RUNTIME_LIBS "Linux: copy the shared libraries the game needs next to it and load them from there" ON)
+endif()
+if (UNIX AND NOT APPLE AND BUNDLE_RUNTIME_LIBS)
+ set_target_properties(${PROJECT_NAME} PROPERTIES
+ BUILD_WITH_INSTALL_RPATH TRUE
+ INSTALL_RPATH "$ORIGIN")
+ target_link_options(${PROJECT_NAME} PRIVATE "LINKER:--disable-new-dtags")
+
+ # the RPATH no longer leads to libraries outside the system folders (Python from setup-python, an OpenAL Soft
+ # in /usr/local), so their folders are given to the script as well
+ set(EU07_BUNDLE_SEARCH_DIRS "")
+ foreach(library IN LISTS Python3_LIBRARIES OPENAL_LIBRARY LUAJIT_LIBRARIES libserialport_LIBRARY)
+ if (IS_ABSOLUTE "${library}")
+ get_filename_component(library_dir "${library}" DIRECTORY)
+ list(APPEND EU07_BUNDLE_SEARCH_DIRS "${library_dir}")
+ endif()
+ endforeach()
+ list(APPEND EU07_BUNDLE_SEARCH_DIRS ${Python3_LIBRARY_DIRS})
+ list(REMOVE_DUPLICATES EU07_BUNDLE_SEARCH_DIRS)
+ string(REPLACE ";" "|" EU07_BUNDLE_SEARCH_DIRS "${EU07_BUNDLE_SEARCH_DIRS}")
+
+ add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
+ COMMAND ${CMAKE_COMMAND}
+ -DGAME=$
+ -DSEARCH_DIRS=${EU07_BUNDLE_SEARCH_DIRS}
+ -DCMAKE_OBJDUMP=${CMAKE_OBJDUMP}
+ -P "${CMAKE_CURRENT_SOURCE_DIR}/CMake_modules/bundle_runtime_libs.cmake"
+ COMMENT "Copying the shared libraries next to the game"
+ VERBATIM)
+endif()
+
if(WIN32 AND WITH_PYTHON)
add_custom_command(
TARGET ${PROJECT_NAME} POST_BUILD
diff --git a/CMake_modules/bundle_runtime_libs.cmake b/CMake_modules/bundle_runtime_libs.cmake
new file mode 100644
index 000000000..a0f71543e
--- /dev/null
+++ b/CMake_modules/bundle_runtime_libs.cmake
@@ -0,0 +1,75 @@
+# copies the shared libraries the game needs next to it, where its RPATH ($ORIGIN) finds them first. Linux only:
+# cmake -DGAME= -DSEARCH_DIRS= [-DCMAKE_OBJDUMP=] -P bundle_runtime_libs.cmake
+#
+# the libraries of the system itself stay out: the C library and the loader, the GPU driver stack (libGL and its
+# kin come with the driver), X11 / Wayland, the sound servers, libstdc++ (the GPU drivers bring their own need of a
+# newer one) and a few more every distribution has. what a library left out depends on isn't bundled either
+
+get_filename_component(game_folder "${GAME}" DIRECTORY)
+set(manifest "${game_folder}/bundled_libs.txt")
+
+# the libraries copied by the previous build go first: the game's RPATH would find them in its folder, and then
+# a library updated in the system would never be copied again
+if(EXISTS "${manifest}")
+ file(STRINGS "${manifest}" previous)
+ foreach(name IN LISTS previous)
+ if(NOT name STREQUAL "")
+ file(REMOVE "${game_folder}/${name}")
+ endif()
+ endforeach()
+ file(REMOVE "${manifest}")
+endif()
+
+string(REPLACE "|" ";" search_dirs "${SEARCH_DIRS}")
+if(DEFINED ENV{LD_LIBRARY_PATH})
+ string(REPLACE ":" ";" ld_library_path "$ENV{LD_LIBRARY_PATH}")
+ list(APPEND search_dirs ${ld_library_path})
+endif()
+list(REMOVE_ITEM search_dirs "")
+list(REMOVE_DUPLICATES search_dirs)
+
+set(system_libraries
+ "^ld-linux"
+ "^linux-vdso"
+ "^lib(c|m|dl|rt|pthread|resolv|util|mvec|anl|nsl|crypt|BrokenLocale|thread_db)\\.so"
+ "^libstdc\\+\\+\\.so"
+ "^libgcc_s\\.so"
+ "^lib(GL|GLX|EGL|OpenGL|GLdispatch|GLESv1_CM|GLESv2|GLU|gbm|drm|vulkan)\\.so"
+ "^libX[A-Za-z0-9_-]*\\.so"
+ "^libxcb"
+ "^libxkbcommon"
+ "^libwayland-"
+ "^libdecor"
+ "^lib(asound|pulse|pulse-simple|jack|pipewire-[0-9.]+)\\.so"
+ "^lib(udev|systemd|dbus-1)\\.so"
+ "^libz\\.so"
+ "^lib(fontconfig|freetype|harfbuzz|expat|uuid)\\.so")
+
+file(GET_RUNTIME_DEPENDENCIES
+ EXECUTABLES "${GAME}"
+ RESOLVED_DEPENDENCIES_VAR resolved
+ UNRESOLVED_DEPENDENCIES_VAR unresolved
+ DIRECTORIES ${search_dirs}
+ PRE_EXCLUDE_REGEXES ${system_libraries})
+
+if(unresolved)
+ list(JOIN unresolved ", " unresolved_text)
+ message(WARNING "Bundled libraries: not found, so not copied next to the game: ${unresolved_text}")
+endif()
+
+# each library is copied under the name the game asks for (libpng16.so.16), as a file rather than the chain of
+# symlinks it is in the system: the build artifacts don't keep symlinks
+set(names "")
+foreach(library IN LISTS resolved)
+ get_filename_component(name "${library}" NAME)
+ file(REAL_PATH "${library}" source)
+ file(COPY_FILE "${source}" "${game_folder}/${name}")
+ list(APPEND names "${name}")
+endforeach()
+
+list(SORT names)
+list(JOIN names "\n" manifest_text)
+file(WRITE "${manifest}" "${manifest_text}\n")
+list(LENGTH names count)
+list(JOIN names " " names_text)
+message("Bundled libraries (${count}): ${names_text}")
diff --git a/EU07.cpp b/EU07.cpp
index e8d226b75..8255c6907 100644
--- a/EU07.cpp
+++ b/EU07.cpp
@@ -23,11 +23,17 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/crashdump.h"
+#include "utilities/physicslog.h"
#include
#include
#include
#include
#include
+#ifdef _WIN32
+#include
+#else
+#include
+#endif
#ifdef _MSC_VER
#ifdef EU07_CPU_PREFLIGHT
@@ -72,6 +78,8 @@ void finish_log()
[[noreturn]] void end_test_run(std::string_view const Reason)
{
simulation::test().conclude(simulation::test_result::error, Reason);
+ // the last two seconds of the physics logs, which the runner of the tests reads
+ PhysicsLogs.stop();
finish_log();
fflush(stdout);
fflush(stderr);
@@ -101,10 +109,29 @@ void finish_log()
end_test_run("the simulator stopped before the test ended");
}
+// the physics logs used to keep a file open for every vehicle with a driver, and on a scenery with some five hundred
+// of them they took all the files the C library of Windows lets a process have open by default (512): the files
+// opened after them, the shaders of the map among them, couldn't be read. they keep none open now (physicslog.h),
+// but the limit is raised to the most either system allows still, for whatever else opens many files at once
+void raise_open_files_limit()
+{
+#ifdef _WIN32
+ _setmaxstdio(8192);
+#else
+ rlimit limit{};
+ if (getrlimit(RLIMIT_NOFILE, &limit) == 0 && limit.rlim_cur < limit.rlim_max)
+ {
+ limit.rlim_cur = limit.rlim_max;
+ setrlimit(RLIMIT_NOFILE, &limit);
+ }
+#endif
+}
+
} // namespace
int main(int argc, char *argv[])
{
+ raise_open_files_limit();
crashdump_install();
// init start timestamp
Global.startTimestamp = std::chrono::steady_clock::now();
@@ -182,6 +209,9 @@ int main(int argc, char *argv[])
MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR);
}
#endif
+ // the last two seconds of the physics logs, also after an error caught above; Application.exit() stops them
+ // otherwise, and a second stop only writes what came since
+ PhysicsLogs.stop();
}
stop_log_service();
#ifndef _WIN32
diff --git a/GEMINI.md b/GEMINI.md
new file mode 100644
index 000000000..bf28f3062
--- /dev/null
+++ b/GEMINI.md
@@ -0,0 +1,5 @@
+# MaSzyna: notes for Gemini CLI
+
+The instructions for every coding agent in this repository are in `AGENTS.md`. Add or change rules there, not here.
+
+@./AGENTS.md
diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h
index 6bea69b0d..d4730f617 100644
--- a/McZapkie/MOVER.h
+++ b/McZapkie/MOVER.h
@@ -14,7 +14,9 @@ http://mozilla.org/MPL/2.0/.
#include
#include
#include "hamulce.h"
+#include "couplerphysics.h"
#include "scripting/ladderlogic.h"
+#include "vehicle/odometerreading.h"
class cParser;
/*
@@ -299,6 +301,16 @@ enum class operation_t
/// Disable button release transition.
disable_off,
};
+/// What else the line contactors of a vehicle need before they can close (LineContactorsInterlock in the Cntrl. section).
+enum class line_contactors_interlock
+{
+ /// Nothing more, the legacy behaviour.
+ none,
+ /// The converter of the vehicle itself running, where it drives the traction motor fans (ET42).
+ converter,
+ /// The traction motor blowers of the vehicle running.
+ motor_blowers
+};
/// Auto-start method for ancillary devices (mutually exclusive).
enum class start_t
{
@@ -1257,6 +1269,7 @@ struct TCoupling
double Dist = 0.0; /*strzalka ugiecia zderzaków*/
bool CheckCollision = false; /*czy sprawdzac sile czy pedy*/
float stretch_duration{0.f}; // seconds, elapsed time with excessive force applied to the coupler
+ bool broken{false}; // the coupler broke (damage_coupler()), until it's repaired (repair_coupler())
// optional adapter piece
double adapter_length{0.0}; // meters, value added on the given end to standard vehicle (half)length
double adapter_height{0.0}; // meters, distance from rail level
@@ -1266,6 +1279,11 @@ struct TCoupling
power_coupling power_110v;
power_coupling power_24v;
+ // the physical model of the coupling (couplerphysics in eu07.ini), see couplerphysics.h: the parameters of this end,
+ // and the state of the coupling with the vehicle at this end, which that vehicle keeps alike on its own end
+ coupler_physics::end_parameters physics;
+ coupler_physics::pair_state physics_state;
+
int sounds{0}; // sounds emitted by the coupling devices
bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/
std::string control_type; // abstraction of control coupling interface and communication standard
@@ -2009,6 +2027,9 @@ class TMoverParameters
glm::vec3 Front{};
std::string Name; /*nazwa wlasna*/
TCoupling Couplers[2]; // urzadzenia zderzno-sprzegowe, polaczenia miedzy wagonami
+ // the physical coupler model covers the vehicle: it's in the player's train or in one the player's train closes in on
+ // (vehicle_table::update_coupler_physics()); with couplerphysics all in eu07.ini every vehicle is covered
+ bool CouplerPhysics{false};
std::array Neighbours; // potential collision sources
bool Power110vIsAvailable = false; // cached availability of 110v power
bool Power24vIsAvailable = false; // cached availability of 110v power
@@ -2017,6 +2038,7 @@ class TMoverParameters
int SoundFlag = 0; /*!o patrz stale sound_ */
int AIFlag{0}; // HACK: events of interest for consist owner
double DistCounter = 0.0; /*! licznik kilometrow */
+ 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 Vel = 0.0; // moduł prędkości w [km/h], używany przez AI
@@ -2114,6 +2136,9 @@ class TMoverParameters
bool UnlockPipe = false; /*unlockig brake pipe button pressed*/
int BrakeDelayFlag = 0; /*nastawa opoznienia ham. osob/towar/posp/exp 0/1/2/4*/
int BrakeDelays = 0; /*nastawy mozliwe do uzyskania*/
+ // 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 BrakeCutOutByInspector = false;
int BrakeOpModeFlag = 0; /*nastawa trybu pracy PS/PN/EP/MED 1/2/4/8*/
int BrakeOpModes = 0; /*nastawy mozliwe do uzyskania*/
bool DynamicBrakeFlag = false; /*czy wlaczony hamulec elektrodymiczny*/
@@ -2150,6 +2175,11 @@ class TMoverParameters
// config, Engine:JointEngineStart. whether the cab's line breaker / engine start switch works the vehicles in multiple
// too; when it doesn't, the cab has separate switches for them (mainb_*, mainc_*)
bool JointEngineStart{true};
+ // config, .fiz 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 (NoVoltRelay)
+ bool PantographsRequireMains{false};
bool LineBreakerClosesOnlyAtNoPowerPos{false};
bool ControlPressureSwitch{false}; // activates if the main pipe and/or brake cylinder pressure aren't within operational levels
bool HasControlPressureSwitch{true};
@@ -2209,13 +2239,17 @@ class TMoverParameters
start_t GroundRelayStart{start_t::manual}; // relay activation method
bool StLinFlag = false; /*!o styczniki liniowe*/
bool StLinSwitchOff{false}; // state of the button forcing motor connectors open
+ line_contactors_interlock LineContactorsInterlock{line_contactors_interlock::none}; // what else the line contactors need to close
+ 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*/
double PantographVoltage{0.0}; // voltage supplied to pantographs
double PantPress = 0.0; /*Cisnienie w zbiornikach pantografow*/
bool PantPressSwitchActive{false}; // state of the pantograph pressure switch. gets primed at defined pressure level in pantograph air system
bool PantPressLockActive{false}; // pwr system state flag. fires when pressure switch activates by pantograph pressure dropping below defined level
- bool NoVoltRelay{true}; // switches off if the power level drops below threshold
+ // switches off if the power level drops below threshold, which opens the line breaker; with PantographsRequireMains
+ // it opens the line contactors instead, and switches back on only with the master controller at zero or the first position
+ bool NoVoltRelay{true};
bool OvervoltageRelay{true}; // switches off if the power level goes above threshold
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
@@ -2385,6 +2419,10 @@ class TMoverParameters
int DettachStatus(int ConnectNo);
bool Dettach(int ConnectNo);
void damage_coupler(int const End);
+ // repairs the broken coupler of the end, and the one of the vehicle it was coupled with, so they can be coupled
+ // again; the vehicles clear their coupler damage once neither of their couplers is broken. returns: whether there
+ // was a broken coupler to repair
+ bool repair_coupler(int const End);
void Derail(DerailReason Reason);
bool DirectionForward();
bool DirectionBackward(void); /*! kierunek ruchu*/
@@ -2547,6 +2585,17 @@ class TMoverParameters
double BrakeForceP(double press, double velocity) const;
double BrakeForce(const TTrackParam &Track);
double CouplerForce(int const End, double dt);
+ // whether the coupling at the end is computed by the physical model: couplerphysics set in eu07.ini, and this
+ // vehicle or the one at the end covered by it (CouplerPhysics), or every vehicle with couplerphysics all
+ bool coupler_physics_at(int const End) const;
+ // the force of the coupling at the end by the physical model (couplerphysics in eu07.ini), see couplerphysics.h
+ double coupler_force_physical(int const End, double const dt);
+ // with the physical model: whether the vehicles at the end hit the stop of their springs at the last update and
+ // still close in on it, so that they collide; a hit hard enough breaks the coupling or crushes the buffers
+ bool coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd);
+ // couples the automatic couplers of the end and of the other vehicle pressed against each other, unless the hit
+ // is too fast for them to catch
+ void automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd);
void CollisionDetect(int const End, double const dt);
// closing speed of a collision [km/h] above which the vehicles involved may derail, adjusted for their mass ratio
static constexpr double SafeCollisionVelocity{15.0};
@@ -2592,6 +2641,26 @@ class TMoverParameters
{
return JointEngineStart ? 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
+ {
+ return Compressor < LouvresOpenPressure;
+ }
+ // whether the devices the line contactors are interlocked with (LineContactorsInterlock) let them close
+ bool LineContactorsInterlockReleased() const;
+ // whether the line contactors wait for the converter of the vehicle, switched off with its local switch (converterlocal_sw).
+ // 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 LineContactorsInterlock == line_contactors_interlock::converter && false == ConverterAllowLocal;
+ }
+ // 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
+ // 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 BrakeHandle != 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
// starts on its own (eu07/maszyna#427). the other vehicles with such a button keep ignoring the command
@@ -2638,6 +2707,11 @@ class TMoverParameters
bool HeatingSwitch(bool const State, range_t const Notify = range_t::consist);
void HeatingSwitch_(bool const State);
double EnginePowerSourceVoltage() const; // returns voltage of defined main engine power source
+ // whether the main circuit feeds what runs on it (the converter, a compressor, the heating, the motor and resistor
+ // blowers, the traction motors): the line breaker closed, and where it closes ahead of the pantographs and holds
+ // without traction voltage (PantographsRequireMains) also the voltage there, at least the one the undervoltage
+ // trip takes. everywhere else it's the same as Mains
+ bool MainCircuitPowered() const;
/*-funkcje typowe dla lokomotywy elektrycznej*/
void LowVoltagePowerCheck(double const Deltatime);
@@ -2650,6 +2724,8 @@ class TMoverParameters
void FuelPumpCheck(double const Timestep);
void OilPumpCheck(double const Timestep);
void MotorBlowersCheck(double const Timestep);
+ // whether the circuit a traction motor blower runs off has power: the battery, the converter or the main circuit, by its start type
+ bool MotorBlowerPowerIsAvailable(cooling_fan const &Blower) const;
void PantographsCheck(double const Timestep);
void LightsCheck(double const Timestep);
bool FuseOn(range_t const Notify = range_t::consist); // bezpiecznik nadamiary
diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp
index 94917b15e..ed8275bc9 100644
--- a/McZapkie/Mover.cpp
+++ b/McZapkie/Mover.cpp
@@ -439,7 +439,7 @@ double TMoverParameters::Current(double n, double U)
// writepaslog("Delta ", FloatToStr(Delta));
// writepaslog("DeltaQ ", FloatToStr(DeltaQ));
// writepaslog("U ", FloatToStr(U));
- if (Mains)
+ if (MainCircuitPowered())
{
if (U > 0)
MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n + std::sqrt(Delta)) / (2.0 * Rz);
@@ -644,6 +644,9 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters *
// stykaja sie zderzaki i kompatybilne typy sprzegow, chyba że łączenie na starcie
if (thiscoupler.CouplingFlag == coupling::faux)
{
+ // a new coupling: the play of the coupling as set up anew, without the stretch of the one before
+ thiscoupler.physics_state.couple();
+ othercoupler.physics_state.couple();
// jeśli wcześniej nie było połączone, ustalenie z której strony rysować sprzęg
thiscoupler.Render = true; // tego rysować
othercoupler.Render = false; // a tego nie
@@ -1335,6 +1338,15 @@ void TMoverParameters::CollisionDetect(int const End, double const dt)
auto const otherend{Neighbours[End].vehicle_end};
auto const &othercoupler{othervehicle->Couplers[otherend]};
+ auto const physical{coupler_physics_at(End)};
+ if (physical && false == coupler_stop_hit(End, *othervehicle, otherend))
+ {
+ return;
+ }
+ // the share of the energy of the relative motion the hit takes: in the physical model the springs gone solid give
+ // for good, rather than spring back as the legacy model has it
+ auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0};
+
// the velocities along this vehicle's axis: the other vehicle's one is turned around when the vehicles face each
// other (touch with the same ends), as in CouplerForce()
auto const otherdirection{DirPatch(End, otherend)};
@@ -1348,12 +1360,12 @@ void TMoverParameters::CollisionDetect(int const End, double const dt)
{
case 0:
{
- CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, (thiscoupler.beta + othercoupler.beta) / 2.0, VirtualCoupling) / dt;
+ CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, loss, VirtualCoupling) / dt;
break; // yB: ej ej ej, a po
}
case 1:
{
- CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, (thiscoupler.beta + othercoupler.beta) / 2.0, VirtualCoupling) / dt;
+ CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, loss, VirtualCoupling) / dt;
break;
}
default:
@@ -1364,7 +1376,8 @@ void TMoverParameters::CollisionDetect(int const End, double const dt)
if (Global.crash_damage)
{
- if (-thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg))
+ // the physical model breaks the coupling and crushes the buffers by the force of the hit (coupler_stop_hit())
+ if (false == physical && -thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg))
{
// small chance to smash the coupler if it's hit with excessive force
damage_coupler(End);
@@ -1393,18 +1406,21 @@ void TMoverParameters::CollisionDetect(int const End, double const dt)
}
}
- // adjust velocity and acceleration of affected vehicles
+ // adjust velocity and acceleration of affected vehicles. the physical model changes the velocities alone: the
+ // integration of the next step (ComputeMovement()) would carry a quarter of an acceleration spike over into the
+ // velocity once more, and the vehicles would bounce off the stop faster than they hit it
+ auto const accelerationspike{physical ? 0.0 : 1.0};
if (false == TestFlag(DamageFlag, dtrain_out))
{
auto const accelerationchange{(velocity - V) / dt};
- AccS += accelerationchange;
+ AccS += accelerationchange * accelerationspike;
V = velocity;
}
if (false == TestFlag(othervehicle->DamageFlag, dtrain_out))
{
auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis
auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->V) / dt};
- othervehicle->AccS += othervehicleaccelerationchange;
+ othervehicle->AccS += othervehicleaccelerationchange * accelerationspike;
othervehicle->V = othervehiclenewvelocity;
}
}
@@ -1422,39 +1438,72 @@ void TMoverParameters::damage_coupler(int const End)
if (SetFlag(DamageFlag, dtrain_coupling))
EventFlag = true;
- if ((thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose)
+ auto const hosetorn{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose};
+ if (hosetorn)
{
// hamowanie nagle - zerwanie przewodow hamulcowych
AlarmChainFlag = true;
}
thiscoupler.CouplingFlag = 0;
+ thiscoupler.broken = true;
if (thiscoupler.Connected != nullptr)
{
- switch (End)
+ // break connection with other vehicle, if there's any: on the end it's coupled with, which is the front one too
+ // for vehicles facing each other
+ auto &othercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]};
+ othercoupler.CouplingFlag = coupling::faux;
+ // the coupling broke between the two, either end can be repaired
+ othercoupler.broken = true;
+ if (hosetorn && coupler_physics_at(End))
{
- // break connection with other vehicle, if there's any
- case 0:
- {
- thiscoupler.Connected->Couplers[end::rear].CouplingFlag = coupling::faux;
- break;
- }
- case 1:
- {
- thiscoupler.Connected->Couplers[end::front].CouplingFlag = coupling::faux;
- break;
- }
- default:
- {
- break;
- }
+ // the brake pipe of the other part of the train vents through the torn hose as well
+ thiscoupler.Connected->AlarmChainFlag = true;
}
}
WriteLog("Bad driving: " + Name + " broke a coupler");
}
+namespace
+{
+
+// the coupler as good as new, the vehicle without the coupler damage (and the emergency braking of the torn brake
+// hose) once neither of its couplers is broken
+void repair(TMoverParameters &Vehicle, TCoupling &Coupler)
+{
+ Coupler.broken = false;
+ Coupler.stretch_duration = 0.f;
+ Coupler.physics_state.couple();
+ if (Vehicle.Couplers[end::front].broken || Vehicle.Couplers[end::rear].broken)
+ {
+ return;
+ }
+ ClearFlag(Vehicle.DamageFlag, dtrain_coupling);
+ // either vehicle of the pair may have been braking through the torn hose
+ Vehicle.AlarmChainFlag = false;
+}
+
+} // namespace
+
+bool TMoverParameters::repair_coupler(int const End)
+{
+ auto &thiscoupler{Couplers[End]};
+ if (false == thiscoupler.broken)
+ {
+ return false;
+ }
+ repair(*this, thiscoupler);
+ // the other half of the coupling, which may be the vehicle flagged with the damage
+ if (auto *other{thiscoupler.Connected}; other != nullptr && other->Couplers[thiscoupler.ConnectedNr].broken)
+ {
+ repair(*other, other->Couplers[thiscoupler.ConnectedNr]);
+ }
+ WriteLog(std::format("Coupler of {} repaired, at its {} end", Name, End == end::front ? "front" : "rear"));
+ return true;
+}
+
void TMoverParameters::Derail(DerailReason const Reason)
{
if (SetFlag(DamageFlag, dtrain_out))
@@ -1597,6 +1646,7 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap
dL)};
DistCounter += fabs(dL) / 1000.0;
+ Odometer.run(dL);
dL = 0;
// koniec procedury, tu nastepuja dodatkowe procedury pomocnicze
@@ -1663,6 +1713,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh
dL)};
DistCounter += fabs(dL) / 1000.0;
+ Odometer.run(dL);
dL = 0;
// koniec procedury, tu nastepuja dodatkowe procedury pomocnicze
@@ -1824,7 +1875,8 @@ void TMoverParameters::MainsCheck(double const Deltatime)
break;
}
}
- auto const maincircuitpowersupply{std::abs(localvoltage) > 0.1 || GetTrainsetHighVoltage() > 0.1};
+ // a line breaker closed ahead of the pantographs gets ready on the low voltage circuits
+ auto const maincircuitpowersupply{std::abs(localvoltage) > 0.1 || GetTrainsetHighVoltage() > 0.1 || (PantographsRequireMains && (Power24vIsAvailable || Power110vIsAvailable))};
if (true == maincircuitpowersupply)
{
@@ -1903,7 +1955,7 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c
case TPowerSource::Main:
{
// HACK: main circuit can be fed through couplers, so we explicitly check pantograph supply here
- localvoltage = true == Mains ? PantographVoltage : 0.0;
+ localvoltage = MainCircuitPowered() ? PantographVoltage : 0.0;
break;
}
default:
@@ -2160,7 +2212,7 @@ void TMoverParameters::ConverterCheck(double const Timestep)
if (ConverterAllow && ConverterAllowLocal && false == ConvOvldFlag &&
false == PantPressLockActive
// HACK: allow carriages to operate converter without (missing) fuse prerequisite
- && (Power > 1.0 ? Mains : GetTrainsetHighVoltage() > 0.0))
+ && (Power > 1.0 ? MainCircuitPowered() : GetTrainsetHighVoltage() > 0.0))
{
// delay timer can be optionally configured, and is set anew whenever converter goes off
if (ConverterStartDelayTimer <= 0.0)
@@ -2246,7 +2298,7 @@ void TMoverParameters::HeatingCheck(double const /*Timestep*/)
}
case TPowerSource::Main:
{
- voltage = true == Mains ? std::max(GetTrainsetHighVoltage(), PantographVoltage) : 0.0;
+ voltage = MainCircuitPowered() ? std::max(GetTrainsetHighVoltage(), PantographVoltage) : 0.0;
break;
}
default:
@@ -2355,9 +2407,7 @@ void TMoverParameters::MotorBlowersCheck(double const Timestep)
}
blower.is_active =
// TODO: bind properly power source when ld is in place
- (blower.start_type == start_t::battery ? Power24vIsAvailable :
- blower.start_type == start_t::converter ? Power110vIsAvailable :
- Mains) // power source
+ MotorBlowerPowerIsAvailable(blower) // power source
// breaker condition disabled until it's implemented in the class data
// && ( true == blower.breaker )
&& false == disable &&
@@ -2387,6 +2437,19 @@ void TMoverParameters::MotorBlowersCheck(double const Timestep)
}
}
+bool TMoverParameters::MotorBlowerPowerIsAvailable(cooling_fan const &Blower) const
+{
+ switch (Blower.start_type)
+ {
+ case start_t::battery:
+ return Power24vIsAvailable;
+ case start_t::converter:
+ return Power110vIsAvailable;
+ default:
+ return MainCircuitPowered();
+ }
+}
+
void TMoverParameters::PantographsCheck(double const /*Timestep*/)
{
using enum start_t;
@@ -2416,7 +2479,8 @@ void TMoverParameters::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 == PantAllDown : true) &&
- (valve.is_active || (manualcontrol && lowvoltagepower && valve.is_enabled) || (autostart && lowvoltagepower)); // shouldn't ever get this far but, eh
+ (Mains || false == PantographsRequireMains) // 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};
@@ -3814,7 +3878,8 @@ bool TMoverParameters::MainSwitchCheck() const
case ElectricInductionMotor:
{
// TODO: check whether we can simplify this check and skip the outer EngineType switch
- powerisavailable = EnginePowerSourceVoltage() > 0.5 * EnginePowerSource.MaxVoltage;
+ // closed ahead of the pantographs, the line breaker runs on the low voltage circuits
+ powerisavailable = PantographsRequireMains ? Power24vIsAvailable || Power110vIsAvailable : EnginePowerSourceVoltage() > 0.5 * EnginePowerSource.MaxVoltage;
break;
}
default:
@@ -3824,7 +3889,8 @@ bool TMoverParameters::MainSwitchCheck() const
}
return powerisavailable && (ScndCtrlPos == 0 || EngineType == ElectricInductionMotor) && MainsInitTimeCountdown <= 0.0 &&
- (ConvOvldFlag == false || ConverterOverloadRelayOffWhenMainIsOff) && true == GroundRelay && true == NoVoltRelay && true == OvervoltageRelay && LastSwitchingTime > CtrlDelay &&
+ (ConvOvldFlag == false || ConverterOverloadRelayOffWhenMainIsOff) && true == GroundRelay && (true == NoVoltRelay || PantographsRequireMains) && true == OvervoltageRelay &&
+ LastSwitchingTime > CtrlDelay &&
(HasCamshaft ? IsMainCtrlActualNoPowerPos() :
LineBreakerClosesOnlyAtNoPowerPos ? IsMainCtrlNoPowerPos() :
true) &&
@@ -3929,6 +3995,25 @@ double TMoverParameters::EnginePowerSourceVoltage() const
0.0;
}
+// whether the main circuit feeds what runs on it: the converter, a compressor, the heating, the motor and resistor
+// blowers, the traction motors
+bool TMoverParameters::MainCircuitPowered() const
+{
+ if (false == Mains)
+ {
+ return false;
+ }
+ if (false == PantographsRequireMains || 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
+ return true;
+ }
+ // closed ahead of the pantographs the line breaker holds without the voltage, which the undervoltage trip isn't
+ // there to vouch for
+ return EnginePowerSourceVoltage() >= EnginePowerSource.CollectorParameters.MinV;
+}
+
// *************************************************************************************************
// Q: 20160711
// zwiększenie nastawy hamulca
@@ -4522,7 +4607,7 @@ void TMoverParameters::CompressorCheck(double dt)
}
// the main circuit, also for a compressor driven by the engine, otherwise the low voltage
- auto const compressorpower{CompressorPower == 0 || CompressorPower == 3 ? Mains : Power110vIsAvailable};
+ auto const compressorpower{CompressorPower == 0 || CompressorPower == 3 ? MainCircuitPowered() : Power110vIsAvailable};
CompressorPowerTime = compressorpower ? CompressorPowerTime + dt : 0.0;
auto const compressorready{compressorpower && CompressorPowerTime >= CompressorStartDelay};
// TBD: split CompressorAllow into separate enable/disable flags, inherit compressor from basic_device
@@ -5495,6 +5580,10 @@ double TMoverParameters::Adhesive(double staticfriction) const
// *************************************************************************************************
double TMoverParameters::CouplerForce(int const End, double dt)
{
+ if (coupler_physics_at(End))
+ {
+ return coupler_force_physical(End, dt);
+ }
auto &thiscoupler{Couplers[End]};
auto *othervehicle{Neighbours[End].vehicle->MoverParameters};
@@ -5608,27 +5697,9 @@ double TMoverParameters::CouplerForce(int const End, double dt)
// zderzenie
thiscoupler.CheckCollision = true;
}
- if (-newdistance >= std::min(collisiondistance, dEpsilon) && thiscoupler.type() == TCouplerType::Automatic && thiscoupler.type() == othercoupler.type() && thiscoupler.CouplingFlag == coupling::faux &&
- thiscoupler.AutomaticCouplingAllowed &&
- othercoupler.AutomaticCouplingAllowed)
+ if (-newdistance >= std::min(collisiondistance, dEpsilon))
{
- // sprzeganie wagonow z samoczynnymi sprzegami
- auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag};
- // potentially exclude incompatible control coupling
- if (thiscoupler.control_type != othercoupler.control_type)
- {
- couplingtype &= ~coupling::control;
- }
- couplingtype = CompatibleCoupling(End, *othervehicle, otherend, couplingtype);
-
- // too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect())
- auto const safe{AutomaticCouplingSafe(End, *othervehicle, otherend)};
- auto const caught{safe && Attach(End, otherend, othervehicle, couplingtype)};
- // HACK: we're reusing sound enum to mark whether vehicle was connected to another
- AIFlag |= (caught ? sound::attachcoupler : 0);
- // coupled, or locked until the vehicles part, so they don't couple as soon as the collision slows them down
- thiscoupler.AutomaticCouplingAllowed = safe && false == caught;
- othercoupler.AutomaticCouplingAllowed = safe && false == caught;
+ automatic_coupling(End, *othervehicle, otherend);
}
}
}
@@ -5643,6 +5714,172 @@ double TMoverParameters::CouplerForce(int const End, double dt)
return CF;
}
+bool TMoverParameters::coupler_physics_at(int const End) const
+{
+ if (false == Global.coupler_physics)
+ {
+ return false;
+ }
+ if (Global.coupler_physics_all || CouplerPhysics)
+ {
+ return true;
+ }
+ // either vehicle of the pair covered takes the pair in, so both of them compute it the same way
+ auto const *other{Neighbours[End].vehicle};
+ return other != nullptr && other->MoverParameters->CouplerPhysics;
+}
+
+void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd)
+{
+ auto &thiscoupler{Couplers[End]};
+ auto &othercoupler{Other.Couplers[OtherEnd]};
+
+ if (thiscoupler.type() != TCouplerType::Automatic || thiscoupler.type() != othercoupler.type() || thiscoupler.CouplingFlag != coupling::faux || false == thiscoupler.AutomaticCouplingAllowed ||
+ false == othercoupler.AutomaticCouplingAllowed)
+ {
+ return;
+ }
+ // sprzeganie wagonow z samoczynnymi sprzegami
+ auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag};
+ // potentially exclude incompatible control coupling
+ if (thiscoupler.control_type != othercoupler.control_type)
+ {
+ couplingtype &= ~coupling::control;
+ }
+ couplingtype = CompatibleCoupling(End, Other, OtherEnd, couplingtype);
+
+ // too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect())
+ auto const safe{AutomaticCouplingSafe(End, Other, OtherEnd)};
+ auto const caught{safe && Attach(End, OtherEnd, &Other, couplingtype)};
+ // HACK: we're reusing sound enum to mark whether vehicle was connected to another
+ AIFlag |= (caught ? sound::attachcoupler : 0);
+ // coupled, or locked until the vehicles part, so they don't couple as soon as the collision slows them down
+ thiscoupler.AutomaticCouplingAllowed = safe && false == caught;
+ othercoupler.AutomaticCouplingAllowed = safe && false == caught;
+}
+
+namespace
+{
+
+// the gap between the ends of a coupled pair, taking up the play of the coupling, opens up enough to jerk the train
+constexpr double coupler_stretch_threshold{0.001};
+
+// the sounds of the buffers hitting each other, and of the coupling taking up its play
+struct coupler_sound_input
+{
+ double gap{0.0}; // between the ends [m]
+ double previous_gap{0.0};
+ double gap_rate{0.0}; // [m/s]
+ double draw_gear{0.0}; // deflection [m]
+ double previous_draw_gear{0.0};
+ bool coupled{false};
+ bool adapter{false};
+ bool moving{false};
+};
+
+int coupler_sounds(coupler_sound_input const &Input)
+{
+ if (Input.gap < 0.0 && Input.gap < Input.previous_gap && Input.gap_rate < -0.1 && false == Input.adapter)
+ {
+ // 090503: dzwieki pracy zderzakow
+ return std::abs(Input.gap_rate) > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash;
+ }
+ if (Input.coupled && Input.moving && Input.draw_gear > coupler_stretch_threshold && Input.previous_draw_gear <= coupler_stretch_threshold && std::abs(Input.gap_rate) > 0.005)
+ {
+ // 090503: dzwieki pracy sprzegu
+ return std::abs(Input.gap_rate) > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch;
+ }
+ return sound::none;
+}
+
+} // namespace
+
+double TMoverParameters::coupler_force_physical(int const End, double const dt)
+{
+ auto &thiscoupler{Couplers[End]};
+ auto *othervehicle{Neighbours[End].vehicle->MoverParameters};
+ auto const otherend{Neighbours[End].vehicle_end};
+ auto &othercoupler{othervehicle->Couplers[otherend]};
+ auto &state{thiscoupler.physics_state};
+
+ // the gap as it is now: the distance found at the start of the frame, and the movement of both vehicles since
+ auto const othervehiclemove{othervehicle->dMoveLen * DirPatch(End, otherend)};
+ auto const gap{Neighbours[End].distance + (End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)};
+ // the gap opens up when the front end falls behind the vehicle ahead of it, or the rear end runs ahead of the one behind
+ auto const gaprate{CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)};
+ auto const coupled{thiscoupler.CouplingFlag != coupling::faux};
+ auto const adapter{thiscoupler.has_adapter() || othercoupler.has_adapter()};
+
+ if (false == coupled && Neighbours[End].distance > 0.05)
+ { // arbitrary distance
+ // potentially reset auto coupling lock
+ thiscoupler.AutomaticCouplingAllowed = true;
+ }
+
+ auto const previousgap{state.gap};
+ auto const previousdrawgear{state.draw_gear.deflection};
+ auto const result{coupler_physics::update_pair(thiscoupler.physics, othercoupler.physics, state, {gap, gaprate, coupled, adapter, Global.crash_damage})};
+
+ SetFlag(thiscoupler.sounds, coupler_sounds({gap, previousgap, gaprate, state.draw_gear.deflection, previousdrawgear, coupled, adapter, Vel > 1.0}));
+
+ thiscoupler.CheckCollision = state.stop != 0;
+ // for the buffers drawn pressed in, see TDynamicObject: twice the deflection of the buffers of this end
+ thiscoupler.Dist = result.compression > 0.0 ? -2.0 * result.buffers_deflection : std::max(gap, 0.0);
+ // the link pulled past its yield force, which the AI drivers ease off on
+ thiscoupler.stretch_duration = result.overloaded ? thiscoupler.stretch_duration + static_cast(dt) : 0.f;
+
+ if (result.broken)
+ {
+ damage_coupler(End);
+ }
+ if (false == coupled && gap < 0.0)
+ {
+ auto const collisiondistance{adapter ? std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : thiscoupler.DmaxB + othercoupler.DmaxB};
+ if (-gap >= std::min(collisiondistance, dEpsilon))
+ {
+ automatic_coupling(End, *othervehicle, otherend);
+ }
+ }
+
+ // tension pulls this vehicle towards the other one
+ auto const force{result.force * -DirF(End)};
+ if (thiscoupler.CouplingFlag != coupling::faux)
+ {
+ // uzgadnianie prawa Newtona, as in CouplerForce()
+ othercoupler.CForce = -force * DirPatch(End, otherend);
+ }
+ return force;
+}
+
+bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd)
+{
+ auto &thiscoupler{Couplers[End]};
+ auto &othercoupler{Other.Couplers[OtherEnd]};
+ auto &state{thiscoupler.physics_state};
+
+ // the draw gear went solid with the gap opening up, the buffers with it closing
+ auto const gaprate{CouplerVelocityDifference(End, Other, OtherEnd) * DirF(End)};
+ auto const closing{state.stop > 0 ? gaprate : -gaprate};
+ if (state.stop == 0 || closing <= 0.0)
+ {
+ // parting from the stop already, after the hit on the other vehicle's end
+ return false;
+ }
+ if (false == Global.crash_damage)
+ {
+ return true;
+ }
+ auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, TotalMass, Other.TotalMass)};
+ // the other vehicle keeps the state of the pair alike
+ othercoupler.physics_state.elongation = state.elongation;
+ if (hit.broken || hit.crushed)
+ {
+ damage_coupler(End);
+ }
+ // a broken coupling lets the vehicles part
+ return false == hit.broken;
+}
+
// *************************************************************************************************
// Q: 20160714
// oblicza sile trakcyjna lokomotywy (dla elektrowozu tez calkowity prad)
@@ -5728,7 +5965,7 @@ double TMoverParameters::TractionForce(double dt)
case TEngineType::ElectricSeriesMotor:
{
- if (true == Mains)
+ if (MainCircuitPowered())
{
switch (RVentType)
{
@@ -5860,11 +6097,18 @@ double TMoverParameters::TractionForce(double dt)
{
// update the state of voltage relays
auto const voltage{std::max(GetTrainsetHighVoltage(), PantographVoltage)};
- NoVoltRelay = EnginePowerSource.SourceType != TPowerSource::CurrentCollector || voltage >= EnginePowerSource.CollectorParameters.MinV;
+ // 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
+ // 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 == PantographsRequireMains || NoVoltRelay || MainCtrlPowerPos() <= 1};
+ NoVoltRelay = EnginePowerSource.SourceType != TPowerSource::CurrentCollector || (voltage >= EnginePowerSource.CollectorParameters.MinV && novoltrelaypicksup);
OvervoltageRelay =
EnginePowerSource.SourceType != TPowerSource::CurrentCollector || voltage <= EnginePowerSource.CollectorParameters.MaxV || false == EnginePowerSource.CollectorParameters.OVP;
// wywalanie szybkiego z powodu niewłaściwego napięcia
- EventFlag |= true == Mains && (false == NoVoltRelay || false == OvervoltageRelay) &&
+ // (a line breaker closed ahead of the pantographs holds without voltage)
+ EventFlag |= true == Mains && ((false == NoVoltRelay && false == PantographsRequireMains) || false == OvervoltageRelay) &&
MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide
break;
}
@@ -5873,7 +6117,8 @@ double TMoverParameters::TractionForce(double dt)
{
// TODO: check if we can use instead the code for electricseriesmotor
// nie wchodzić w funkcję bez potrzeby
- if (Mains && (std::max(GetTrainsetHighVoltage(), PantographVoltage) < EnginePowerSource.CollectorParameters.MinV ||
+ // (a line breaker closed ahead of the pantographs holds without voltage)
+ if (Mains && ((std::max(GetTrainsetHighVoltage(), PantographVoltage) < EnginePowerSource.CollectorParameters.MinV && false == PantographsRequireMains) ||
std::max(GetTrainsetHighVoltage(), PantographVoltage) > EnginePowerSource.CollectorParameters.MaxV + 200))
{
MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide
@@ -6394,7 +6639,7 @@ double TMoverParameters::TractionForce(double dt)
case TEngineType::ElectricInductionMotor:
{
- if (true == Mains && !SecuritySystem.is_engine_blocked())
+ if (MainCircuitPowered() && !SecuritySystem.is_engine_blocked())
{
double ActiveInverters = 0.0;
for (auto const &inv : Inverters)
@@ -7312,9 +7557,36 @@ bool TMoverParameters::MotorConnectorsCheck()
return false;
}
- auto const connectorsoff{false == Mains || true == FuseFlag || true == StLinSwitchOff || DirActive == 0};
+ // 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{PantographsRequireMains && false == NoVoltRelay};
- return false == connectorsoff;
+ auto const connectorsoff{false == Mains || undervoltage || true == FuseFlag || true == StLinSwitchOff || DirActive == 0};
+
+ return false == connectorsoff && LineContactorsInterlockReleased();
+}
+
+bool TMoverParameters::LineContactorsInterlockReleased() const
+{
+ switch (LineContactorsInterlock)
+ {
+ 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 ConverterFlag;
+ case line_contactors_interlock::motor_blowers:
+ return std::ranges::all_of(MotorBlowers, [this](auto const &Blower) {
+ if (Blower.min_start_velocity < 0)
+ {
+ return Blower.is_active;
+ }
+ // a blower which starts with the speed and the motor current (MotorBlowersStartVelocity) can't run before
+ // the contactors close, nor after a stop longer than it keeps running for: it's enough that it's
+ // switched on and has power, so it starts once the vehicle moves
+ return MotorBlowerPowerIsAvailable(Blower) && false == Blower.is_disabled && (Blower.start_type == start_t::manual ? Blower.is_enabled : true);
+ });
+ default:
+ return true;
+ }
}
bool TMoverParameters::OperatePantographsValve(operation_t const State, range_t const Notify)
@@ -7687,7 +7959,7 @@ void TMoverParameters::CheckEIMIC(double dt)
eimic = 0;
}
- auto const eimicpowerenabled{(true == Mains || Power == 0.0) && (!SpringBrake.IsActive || !SpringBrakeCutsOffDrive) && !LockPipe && DirAbsolute != 0};
+ auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!SpringBrake.IsActive || !SpringBrakeCutsOffDrive) && !LockPipe && DirAbsolute != 0};
auto const eimicdoorenabled{(SpringBrake.IsActive && ReleaseParkingBySpringBrakeWhenDoorIsOpen)};
double eimic_max = 0.0;
if (Doors.instances[side::left].open_permit == false && Doors.instances[side::right].open_permit == false)
@@ -11012,6 +11284,82 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &line)
extract_value(DoorsPermitLightBlinking, "DoorsPermitLightBlinking", line, "");
}
+namespace
+{
+
+// the value of an optional key of the line, or the default without it
+double optional_value(std::string const &Line, std::string const &Key, double const Default)
+{
+ auto value{Default};
+ extract_value(value, Key, Line, "");
+ return value;
+}
+
+// the value of an optional key of the line given in kilo-units, in units; or the default (in units) without it
+double optional_kilo_value(std::string const &Line, std::string const &Key, double const Default)
+{
+ auto value{0.0};
+ return extract_value(value, Key, Line, "") && value > 0.0 ? value * 1000.0 : Default;
+}
+
+// the play of a coupling as made, for each kind: a screw coupling is tightened so that the buffers touch, the knuckles of
+// an automatic coupler have about a centimetre between them, a chain hangs loose
+double default_slack(TCouplerType const Type)
+{
+ switch (Type)
+ {
+ case TCouplerType::Automatic:
+ return 0.005;
+ case TCouplerType::Chain:
+ return 0.05;
+ default:
+ return 0.0;
+ }
+}
+
+// the parameters of the physical model of the coupling (couplerphysics in eu07.ini, see couplerphysics.h), taken from
+// those of the legacy model, and the optional keys of the .fiz for what the legacy model doesn't have:
+// Slack [m] the play of the coupling of this end, negative for a screw coupling tightened to press the buffers in
+// ProgB, ProgC [-] progression of the buffers and of the draw gear, 0 linear, up to 0.9
+// UnloadB, UnloadC [-] force of the unloading curve of the buffers and of the draw gear to that of the loading one
+// FyieldC [kN] the force past which the link stretches for good; DbreakC [m] the elongation at which it breaks
+// kL [kN/m] stiffness of the steel parts past the travel of the springs; FcrushB [kN] the buffers give under it
+// RestitutionSolid [-] coefficient of restitution of a hit on the springs gone solid
+coupler_physics::end_parameters coupler_physics_parameters(TCoupling const &Coupler, std::string const &Line)
+{
+ coupler_physics::end_parameters parameters;
+ parameters.buffers = {Coupler.SpringKB, Coupler.DmaxB, std::clamp(optional_value(Line, "ProgB", 0.5), 0.0, 0.9)};
+ parameters.draw_gear = {Coupler.SpringKC, Coupler.DmaxC, std::clamp(optional_value(Line, "ProgC", 0.3), 0.0, 0.9)};
+ // only a screw coupling can be tightened to press the buffers in, and not past their travel
+ auto const tightest{Coupler.CouplerType == TCouplerType::Screw ? -Coupler.DmaxB : 0.0};
+ parameters.slack = std::max(optional_value(Line, "Slack", default_slack(Coupler.CouplerType)), tightest);
+ // the legacy model sprang back at beta of the force it was loaded with
+ auto const unloading{Coupler.beta > 0.0 && Coupler.beta < 1.0 ? Coupler.beta : 0.5};
+ parameters.buffers_unloading = std::clamp(optional_value(Line, "UnloadB", unloading), 0.05, 1.0);
+ parameters.draw_gear_unloading = std::clamp(optional_value(Line, "UnloadC", unloading), 0.05, 1.0);
+ // as much as the legacy model had
+ parameters.damping = CouplerTune * (Coupler.FmaxC + Coupler.FmaxB) * std::max(Coupler.beta, 0.0);
+
+ // FmaxC is the rated breaking force of the coupling
+ auto const ultimate{std::max(Coupler.FmaxC, 1.0)};
+ auto const yield{std::min(optional_kilo_value(Line, "FyieldC", 0.8 * ultimate), ultimate)};
+ auto const elongation{std::max(optional_value(Line, "DbreakC", 0.02), 0.001)};
+ parameters.link = {yield, ultimate, std::max((ultimate - yield) / elongation, 1.0), Coupler.CouplerType != TCouplerType::Articulated};
+ // the steel parts give a few millimetres under the rated force
+ parameters.link_stiffness = optional_kilo_value(Line, "kL", ultimate / 0.003);
+ parameters.crush_force = optional_kilo_value(Line, "FcrushB", 2.5 * std::max(Coupler.FmaxB, Coupler.FmaxC));
+ parameters.solid_restitution = std::clamp(optional_value(Line, "RestitutionSolid", parameters.solid_restitution), 0.05, 0.95);
+ return parameters;
+}
+
+void scale_strength(coupler_physics::link_strength &Link, double const Factor)
+{
+ Link.yield *= Factor;
+ Link.ultimate *= Factor;
+}
+
+} // namespace
+
void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Index)
{
@@ -11090,11 +11438,21 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde
thiscoupler->DmaxB = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKB);
}
+ thiscoupler->physics = coupler_physics_parameters(*thiscoupler, line);
+
if (Index == 0)
{
// 0 indicates single entry for both couplers
Couplers[1] = Couplers[0];
}
+ // each coupling as made is a little stronger than its rated force, a different one at each end
+ for (int end = end::front; end <= end::rear; ++end)
+ {
+ if (Index == 0 || end == (Index == 2 ? end::rear : end::front))
+ {
+ scale_strength(Couplers[end].physics.link, coupler_physics::strength_scatter(Name, end));
+ }
+ }
}
void TMoverParameters::LoadFIZ_TurboPos(std::string const &Input)
@@ -11321,6 +11679,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line)
auto lookup = starts.find(extract_value("MainStart", line));
MainsStart = lookup != starts.end() ? lookup->second : start_t::manual;
}
+ extract_value(PantographsRequireMains, "PantRequiresMain", line, "");
// battery
{
auto lookup = starts.find(extract_value("BatteryStart", line));
@@ -11388,6 +11747,14 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line)
MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : start_t::manual;
MotorBlowers[end::front].start_type = MotorBlowers[end::rear].start_type;
}
+ // what else the line contactors need to close
+ {
+ std::map> const interlocks{{"Converter", line_contactors_interlock::converter},
+ {"MotorBlowers", line_contactors_interlock::motor_blowers}};
+ auto lookup = interlocks.find(extract_value("LineContactorsInterlock", line));
+ LineContactorsInterlock = lookup != interlocks.end() ? lookup->second : line_contactors_interlock::none;
+ }
+ extract_value(LouvresOpenPressure, "LouvresOpenPressure", line, "");
// compartment lights
{
auto lookup = starts.find(extract_value("CompartmentLightsStart", line));
diff --git a/McZapkie/couplerphysics.cpp b/McZapkie/couplerphysics.cpp
new file mode 100644
index 000000000..f6a226b55
--- /dev/null
+++ b/McZapkie/couplerphysics.cpp
@@ -0,0 +1,291 @@
+/*
+This Source Code Form is subject to the
+terms of the Mozilla Public License, v.
+2.0. If a copy of the MPL was not
+distributed with this file, You can
+obtain one at
+http://mozilla.org/MPL/2.0/.
+*/
+
+#include "stdafx.h"
+#include "couplerphysics.h"
+
+#include
+#include
+#include
+#include
+
+namespace coupler_physics {
+
+namespace {
+
+// the transition between the loading and the unloading curve of a device, to the secant stiffness of the pair: the
+// friction holds the device stiffer than its springs until the force changes enough to slip it
+constexpr double transition_factor{3.0};
+// the force, the deflection and the energy of a curve are computed within this many iterations of the inverse
+constexpr int inverse_iterations{50};
+constexpr int series_iterations{60};
+
+// a device which doesn't give at all, standing in for the buffers of an end with an adapter
+constexpr spring_curve rigid{1.0, 0.0, 0.0};
+
+double series_stiffness(double First, double Second) {
+ return First * Second / (First + Second);
+}
+
+// the buffers of the pair: those of both ends in series, or with an adapter on either end, the device with the shorter
+// travel alone, the one of the automatic coupler which takes the push
+struct pressed_devices {
+ spring_curve first;
+ spring_curve second;
+ double unloading{0.5};
+ double damping{0.0};
+};
+
+bool shorter(spring_curve const &First, spring_curve const &Second) {
+ return std::tie(First.travel, First.stiffness, First.progression) <= std::tie(Second.travel, Second.stiffness, Second.progression);
+}
+
+pressed_devices buffers_of(end_parameters const &First, end_parameters const &Second, bool const Adapter) {
+ auto const unloading{0.5 * (First.buffers_unloading + Second.buffers_unloading)};
+ auto const damping{0.5 * (First.damping + Second.damping)};
+ if (false == Adapter) {
+ return {First.buffers, Second.buffers, unloading, damping};
+ }
+ auto const &coupler{shorter(First.buffers, Second.buffers) ? First.buffers : Second.buffers};
+ return {coupler, rigid, unloading, damping};
+}
+
+pressed_devices draw_gears_of(end_parameters const &First, end_parameters const &Second) {
+ return {First.draw_gear, Second.draw_gear, 0.5 * (First.draw_gear_unloading + Second.draw_gear_unloading), 0.5 * (First.damping + Second.damping)};
+}
+
+struct pressed_force {
+ double force{0.0}; // with the friction and the damping [N]
+ double curve_force{0.0}; // of the loading curve [N]
+ double first_deflection{0.0}; // of the first device [m]
+ bool solid{false}; // both devices at the end of their travel
+};
+
+// the force of the devices pressed (or pulled) by the deflection growing at the rate
+pressed_force press(pressed_devices const &Devices, hysteresis &State, double const Deflection, double const Rate) {
+ if (Deflection <= 0.0) {
+ State.reset();
+ return {};
+ }
+ auto const split{series(Devices.first, Devices.second, Deflection)};
+ auto const travel{Devices.first.travel + Devices.second.travel};
+ auto const top{std::max(Devices.first.end_force(), Devices.second.end_force())};
+ auto const transition{transition_factor * top / std::max(travel, 1e-3)};
+ auto const friction{State.update(Deflection, split.force, Devices.unloading * split.force, transition)};
+ // a buffer pushes, a draw gear pulls, neither the other way round however fast they spring back
+ return {std::max(0.0, friction + Devices.damping * Rate), split.force, split.first, Deflection >= travel};
+}
+
+bool weaker(link_strength const &First, link_strength const &Second) {
+ return std::tie(First.ultimate, First.yield, First.hardening) <= std::tie(Second.ultimate, Second.yield, Second.hardening);
+}
+
+} // namespace
+
+double spring_curve::force(double const Deflection) const {
+ if (travel <= 0.0 || Deflection <= 0.0) {
+ return 0.0;
+ }
+ auto const u{std::min(Deflection / travel, 1.0)};
+ return end_force() * ((1.0 - progression) * u + progression * u * u * u);
+}
+
+double spring_curve::deflection(double const Force) const {
+ if (travel <= 0.0 || Force <= 0.0) {
+ return 0.0;
+ }
+ auto const f{Force / end_force()};
+ if (f >= 1.0) {
+ return travel;
+ }
+ if (progression <= 0.0) {
+ return f * travel;
+ }
+ // the curve is rising and convex, so Newton's method from the end of the travel closes in from above
+ auto u{1.0};
+ auto step{1.0};
+ for (int iteration = 0; iteration < inverse_iterations && std::abs(step) > 1e-15; ++iteration) {
+ auto const value{progression * u * u * u + (1.0 - progression) * u - f};
+ auto const slope{3.0 * progression * u * u + (1.0 - progression)};
+ step = value / slope;
+ u -= step;
+ }
+ return std::clamp(u, 0.0, 1.0) * travel;
+}
+
+double spring_curve::energy(double const Deflection) const {
+ if (travel <= 0.0 || Deflection <= 0.0) {
+ return 0.0;
+ }
+ auto const u{std::min(Deflection / travel, 1.0)};
+ return end_force() * travel * ((1.0 - progression) * u * u / 2.0 + progression * u * u * u * u / 4.0);
+}
+
+series_split series(spring_curve const &First, spring_curve const &Second, double const Deflection) {
+ if (Deflection <= 0.0) {
+ return {};
+ }
+ if (Second.travel <= 0.0) {
+ return {First.force(Deflection), std::min(Deflection, First.travel), 0.0};
+ }
+ if (First.travel <= 0.0) {
+ return {Second.force(Deflection), 0.0, std::min(Deflection, Second.travel)};
+ }
+ if (std::tie(First.stiffness, First.travel, First.progression) == std::tie(Second.stiffness, Second.travel, Second.progression)) {
+ auto const half{std::min(Deflection / 2.0, First.travel)};
+ return {First.force(half), half, half};
+ }
+ auto const top{std::max(First.end_force(), Second.end_force())};
+ if (Deflection >= First.travel + Second.travel) {
+ return {top, First.travel, Second.travel};
+ }
+ // the force at which the deflections of both add up to the given one. the sum doesn't depend on the order of
+ // the devices, so neither does the result
+ auto low{0.0};
+ auto high{top};
+ for (int iteration = 0; iteration < series_iterations; ++iteration) {
+ auto const middle{0.5 * (low + high)};
+ if (First.deflection(middle) + Second.deflection(middle) < Deflection) {
+ low = middle;
+ }
+ else {
+ high = middle;
+ }
+ }
+ auto const force{0.5 * (low + high)};
+ return {force, First.deflection(force), Second.deflection(force)};
+}
+
+double hysteresis::update(double const Deflection, double const Loading, double const Unloading, double const Transition) {
+ force = std::clamp(force + Transition * (Deflection - deflection), std::min(Unloading, Loading), Loading);
+ deflection = Deflection;
+ return force;
+}
+
+void hysteresis::reset() {
+ force = 0.0;
+ deflection = 0.0;
+}
+
+double plastic_elongation(link_strength const &Link, double const Force, double const Elongation) {
+ if (false == Link.breakable || Force <= Link.yield) {
+ return Elongation;
+ }
+ return std::max(Elongation, (Force - Link.yield) / Link.hardening);
+}
+
+double impact_force(double const Velocity, double const Stiffness, double const Mass1, double const Mass2) {
+ if (Velocity <= 0.0 || Mass1 <= 0.0 || Mass2 <= 0.0) {
+ return 0.0;
+ }
+ auto const mass{Mass1 * Mass2 / (Mass1 + Mass2)};
+ return Velocity * std::sqrt(Stiffness * mass);
+}
+
+double strength_scatter(std::string_view const Name, int const End) {
+ // FNV-1a, which std::hash isn't on every compiler
+ std::uint64_t hash{14695981039346656037ULL};
+ auto const mix = [&hash](unsigned char const Byte) {
+ hash ^= Byte;
+ hash *= 1099511628211ULL;
+ };
+ for (auto const character : Name) {
+ mix(static_cast(character));
+ }
+ mix(static_cast(End));
+ // the 53 high bits, as a fraction
+ auto const fraction{static_cast(hash >> 11) / 9007199254740992.0};
+ return 1.0 + 0.2 * fraction;
+}
+
+link_strength weaker_link(end_parameters const &First, end_parameters const &Second) {
+ auto link{weaker(First.link, Second.link) ? First.link : Second.link};
+ // an articulated joint holds whatever the end of the other section is set up to
+ link.breakable = First.link.breakable && Second.link.breakable;
+ return link;
+}
+
+double solid_hit_loss(end_parameters const &First, end_parameters const &Second) {
+ // the collision needs some bounce left (ComputeCollision() asserts it)
+ auto const restitution{std::clamp(0.5 * (First.solid_restitution + Second.solid_restitution), 0.05, 0.95)};
+ return 1.0 - restitution * restitution;
+}
+
+void pair_state::couple() {
+ draw_gear.reset();
+ elongation = 0.0;
+}
+
+pair_result update_pair(end_parameters const &First, end_parameters const &Second, pair_state &State, pair_input const &Input) {
+ pair_result result;
+ State.stop = 0;
+ State.stop_force = 0.0;
+
+ pressed_force pulled;
+ if (Input.coupled) {
+ auto const play{First.slack + Second.slack + State.elongation};
+ pulled = press(draw_gears_of(First, Second), State.draw_gear, Input.gap - play, Input.gap_rate);
+ }
+ else {
+ State.draw_gear.reset();
+ }
+ auto const pushed{press(buffers_of(First, Second, Input.adapter), State.buffers, -Input.gap, -Input.gap_rate)};
+
+ result.tension = pulled.force;
+ result.compression = pushed.force;
+ result.buffers_deflection = Input.adapter ? 0.0 : pushed.first_deflection;
+ if (pulled.solid) {
+ State.stop = 1;
+ State.stop_force = pulled.curve_force;
+ }
+ else if (pushed.solid) {
+ State.stop = -1;
+ State.stop_force = pushed.curve_force;
+ }
+
+ if (Input.coupled) {
+ auto const link{weaker_link(First, Second)};
+ result.overloaded = result.tension > link.yield;
+ if (Input.damage && link.breakable && result.tension >= link.ultimate) {
+ result.broken = true;
+ result.tension = 0.0;
+ State.draw_gear.reset();
+ State.stop = std::min(State.stop, 0);
+ }
+ else if (Input.damage) {
+ State.elongation = plastic_elongation(link, result.tension, State.elongation);
+ }
+ }
+
+ result.force = result.tension - result.compression;
+ State.gap = Input.gap;
+ return result;
+}
+
+impact_result impact(end_parameters const &First, end_parameters const &Second, pair_state &State, double const Velocity, double const Mass1, double const Mass2) {
+ impact_result result;
+ if (State.stop == 0 || Velocity <= 0.0) {
+ return result;
+ }
+ auto const stiffness{series_stiffness(First.link_stiffness, Second.link_stiffness)};
+ result.force = State.stop_force + impact_force(Velocity, stiffness, Mass1, Mass2);
+ if (State.stop > 0) {
+ auto const link{weaker_link(First, Second)};
+ result.broken = link.breakable && result.force >= link.ultimate;
+ if (false == result.broken) {
+ State.elongation = plastic_elongation(link, result.force, State.elongation);
+ }
+ }
+ else {
+ result.crushed = result.force >= std::min(First.crush_force, Second.crush_force);
+ }
+ return result;
+}
+
+} // namespace coupler_physics
diff --git a/McZapkie/couplerphysics.h b/McZapkie/couplerphysics.h
new file mode 100644
index 000000000..47789aba2
--- /dev/null
+++ b/McZapkie/couplerphysics.h
@@ -0,0 +1,140 @@
+#pragma once
+
+#include
+#include
+
+// the physical model of the coupling of two vehicles, used with couplerphysics set in eu07.ini (the legacy model of
+// TMoverParameters::CouplerForce() otherwise). each vehicle end brings its buffers and its draw gear: progressive
+// springs with friction hysteresis, pressed in series against those of the other end. the coupling has play (slack)
+// in tension, or pulls the buffers in when its screw is tightened, and its steel link stretches for good past its
+// yield force and breaks at its ultimate one, under a steady pull or the jerk of a run-out of the slack
+namespace coupler_physics {
+
+// force-deflection characteristic of the spring device of one vehicle end, its buffers or its draw gear:
+// F(d) = F_end * ((1 - p) * u + p * u^3), u = d / travel, F_end = stiffness * travel
+// p (the progression) 0 gives a linear spring; towards 1 it's soft at first and stiffens towards the end of the
+// travel, as ring springs and elastomer pads do
+struct spring_curve {
+ double stiffness{1.0}; // secant stiffness, up to the end of the travel [N/m]
+ double travel{0.1}; // [m]
+ double progression{0.0}; // 0 to 0.9
+
+ double end_force() const { return stiffness * travel; }
+ // force at the deflection [N], the deflection held within the travel
+ double force(double Deflection) const;
+ // deflection at the force [m]: the end of the travel at the end force and past it
+ double deflection(double Force) const;
+ // energy the device takes in along the curve up to the deflection [J]
+ double energy(double Deflection) const;
+};
+
+// the devices of both ends pressed against each other: they carry the same force, their deflections add up. past
+// the end of the travel of one, the other one takes the rest. the result doesn't depend on the order of the two
+struct series_split {
+ double force{0.0}; // [N]
+ double first{0.0}; // deflection of the first device [m]
+ double second{0.0}; // of the second one [m]
+};
+series_split series(spring_curve const &First, spring_curve const &Second, double Deflection);
+
+// friction (Coulomb) hysteresis of a spring device: the force follows the loading curve while the deflection grows,
+// drops to the unloading curve when it shrinks, and in between moves along a stiff transition line, as the friction
+// of ring springs or of the wedges of a draw gear holds the device until the force changes enough
+struct hysteresis {
+ double force{0.0}; // carried at the last update [N]
+ double deflection{0.0}; // at the last update [m]
+
+ // the force at the new deflection, given the force of the loading and of the unloading curve there, and the
+ // stiffness of the transition between them [N/m]
+ double update(double Deflection, double Loading, double Unloading, double Transition);
+ void reset();
+};
+
+// steel link of the coupling (the screw coupling and the hook, the knuckle of an automatic coupler): elastic up to
+// the yield force, stretched for good past it (the hardening gives the force for each metre of it), broken at the
+// ultimate force
+struct link_strength {
+ double yield{std::numeric_limits::max()}; // [N]
+ double ultimate{std::numeric_limits::max()}; // [N]
+ double hardening{1.0}; // [N/m]
+ bool breakable{false}; // an articulated joint, or an end without a coupler set up, holds whatever
+};
+
+// the permanent elongation [m] the link has after carrying the force, given the one it had
+double plastic_elongation(link_strength const &Link, double Force, double Elongation);
+// peak force [N] of an elastic hit of two masses [kg] at the closing velocity [m/s] on a stop of the stiffness [N/m]:
+// the kinetic energy of their relative motion all goes into the stop
+double impact_force(double Velocity, double Stiffness, double Mass1, double Mass2);
+// spread of the strength of the couplings as made: 1.0 to 1.2 of the rated force, fixed for the vehicle end, and the
+// same on every compiler
+double strength_scatter(std::string_view Name, int End);
+
+// what the model takes of one vehicle end
+struct end_parameters {
+ spring_curve buffers;
+ spring_curve draw_gear;
+ double slack{0.0}; // play of the coupling in tension [m], negative for the buffers pressed in by a tightened screw coupling
+ double buffers_unloading{0.5}; // force of the unloading curve to that of the loading one
+ double draw_gear_unloading{0.5};
+ double damping{0.0}; // viscous damping of the devices, while pressed [N s/m]
+ double link_stiffness{1.0}; // of the steel parts of the end, past the travel of the springs [N/m]
+ double crush_force{std::numeric_limits::max()}; // a hit on the buffers past their travel with this force crushes them [N]
+ // coefficient of restitution of a hit on the springs gone solid: the steel of the housings and the underframe gives
+ // for good rather than springing back, so the vehicles share their momentum rather than pass it on
+ double solid_restitution{0.2};
+ link_strength link;
+};
+
+// the share of the energy of the relative motion a hit on the solid springs of the two ends takes, as the legacy
+// collision (ComputeCollision()) takes it: 1 - e^2
+double solid_hit_loss(end_parameters const &First, end_parameters const &Second);
+
+// the weaker of the links of the two ends, which gives first; the same whichever end asks
+link_strength weaker_link(end_parameters const &First, end_parameters const &Second);
+
+// state of the coupling of two vehicle ends, which both vehicles keep alike: each updates its own copy with the same
+// gap, so the copies stay the same
+struct pair_state {
+ hysteresis draw_gear;
+ hysteresis buffers;
+ double elongation{0.0}; // permanent, of the link [m]; it adds to the slack until the vehicles are coupled again
+ double gap{0.0}; // at the last update [m]
+ int stop{0}; // at the last update: 1 the draw gear went solid, -1 the buffers did, 0 neither
+ double stop_force{0.0}; // the springs carried at the stop [N]
+
+ // a new coupling of the ends: the link adjusted (a screw coupling tightened anew), the draw gear released
+ void couple();
+};
+
+struct pair_input {
+ double gap{0.0}; // between the ends [m], negative with the buffers pressed in
+ double gap_rate{0.0}; // [m/s]
+ bool coupled{false};
+ bool adapter{false}; // an adapter on either end: the buffers don't meet, the coupler takes the push alone
+ bool damage{false}; // the link can stretch and break (crash damage on)
+};
+
+struct pair_result {
+ double force{0.0}; // between the ends, tension positive [N]
+ double tension{0.0}; // carried by the link [N]
+ double compression{0.0}; // carried by the buffers [N]
+ double buffers_deflection{0.0}; // of the buffers of the first end [m]
+ bool overloaded{false}; // the link was pulled past its yield force
+ bool broken{false}; // the link broke, it carries nothing now
+};
+
+// the force between the first end and the second one at the gap, updating the state of the pair
+pair_result update_pair(end_parameters const &First, end_parameters const &Second, pair_state &State, pair_input const &Input);
+
+// what a hit on the stop does to the ends
+struct impact_result {
+ double force{0.0}; // peak force of the hit [N]
+ bool broken{false}; // the link broke under it
+ bool crushed{false}; // the buffers or the coupler of an end were crushed by it
+};
+
+// the hit on the stop the pair went solid against at the last update (State.stop), at the closing velocity [m/s], of
+// the vehicles of the masses [kg]: stretches or breaks the link of a coupled pair, may crush the buffers
+impact_result impact(end_parameters const &First, end_parameters const &Second, pair_state &State, double Velocity, double Mass1, double Mass2);
+
+} // namespace coupler_physics
diff --git a/McZapkie/hamulce.cpp b/McZapkie/hamulce.cpp
index 9411dc425..b30372e5e 100644
--- a/McZapkie/hamulce.cpp
+++ b/McZapkie/hamulce.cpp
@@ -1467,7 +1467,7 @@ double TESt4R::GetPF(double const PP, double const dt, double const Vel)
result = dv - dV1;
- RapidStatus = BrakeDelayFlag == bdelay_R && ((Vel > 55 && RapidStatus == true) || Vel > 70);
+ RapidStatus = (BrakeDelayFlag & bdelay_R) == bdelay_R && ((Vel > 55 && RapidStatus == true) || Vel > 70);
RapidTemp = RapidTemp + (0.9 * int(RapidStatus) - RapidTemp) * dt / 2;
temp = 1.9 - RapidTemp;
@@ -1770,7 +1770,7 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel)
// if Vel>55 then temp:=0.72 else
// temp:=1;{R}
// cisnienie PP
- RapidTemp = RapidTemp + (RM * int(Vel > 55 && BrakeDelayFlag == bdelay_R) - RapidTemp) * dt / 2;
+ RapidTemp = RapidTemp + (RM * int(Vel > 55 && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2;
temp = 1 - RapidTemp;
if (EDFlag > 0.2)
temp = 10000;
@@ -1989,7 +1989,7 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel)
dv = dv + PF(MPP, VVP, 0.02);
Miedzypoj->Flow(dv * dt * 0.15);
- RapidTemp = RapidTemp + (RM * int(Vel > RV && BrakeDelayFlag == bdelay_R) - RapidTemp) * dt / 2;
+ RapidTemp = RapidTemp + (RM * int(Vel > RV && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2;
temp = std::max(1 - RapidTemp, 0.001);
// if EDFlag then temp:=1000;
// temp:=temp/(1-);
diff --git a/application/application.cpp b/application/application.cpp
index 01b2ce9a6..bed4bf3ae 100644
--- a/application/application.cpp
+++ b/application/application.cpp
@@ -18,12 +18,14 @@ http://mozilla.org/MPL/2.0/.
#include "utilities/utilities.h"
#include "simulation/simulation.h"
#include "simulation/simulationsounds.h"
+#include "simulation/blackboxrecorder.h"
#include "vehicle/Train.h"
#include "utilities/dictionary.h"
#include "scene/sceneeditor.h"
#include "rendering/renderer.h"
#include "application/uilayer.h"
#include "utilities/Logs.h"
+#include "world/SleeperWorker.h"
#include "rendering/screenshot.h"
#include "utilities/translation.h"
#include "vehicle/Train.h"
@@ -33,6 +35,7 @@ http://mozilla.org/MPL/2.0/.
#include "utilities/dictionary.h"
#include "version_info.h"
#include "simulation/simulationtest.h"
+#include "utilities/physicslog.h"
#include
#include
#include
@@ -747,6 +750,14 @@ void eu07_application::exit()
auto const step = [closing](char const *What) {
WriteLog(std::format("Closing: {} at {} ms", What, std::chrono::duration_cast(std::chrono::steady_clock::now() - closing).count()));
};
+ step("the sleepers laid in the background");
+ // the sleepers laid in the background read the scenery, which goes below
+ track_sleepers::stop_background();
+ step("the black box");
+ simulation::Blackbox.close();
+ step("the physics logs");
+ // what is kept of them, the black box's written last
+ PhysicsLogs.stop();
step("the modes");
for (auto &mode : m_modes)
mode.reset();
@@ -758,6 +769,8 @@ void eu07_application::exit()
m_network.reset();
// SafeDelete( simulation::Train );
+ step("the odometers");
+ simulation::Vehicles.save_odometers();
step("the scenery");
SafeDelete(simulation::Region);
@@ -1436,9 +1449,9 @@ int eu07_application::create_main_window()
Global.bFullScreen = true;
}
- // a selftest of the editor run while the computer is in use for something else draws into a window never shown nor focused,
- // and test mode keeps its window hidden: glfw, the ui and the input still need one, but nothing is shown in it
- bool const shown{std::getenv("EU07_EDITOR_SELFTEST_HIDDEN") == nullptr && false == Global.test.enabled};
+ // test mode keeps its window hidden: glfw, the ui and the input still need one, but nothing is shown in it.
+ // so does a selftest of the editor run while the computer is in use for something else: never shown nor focused
+ bool const shown{false == Global.test.enabled && selftest_script("EU07_EDITOR_SELFTEST_HIDDEN") == nullptr};
auto *mainwindow = window(-1, shown, Global.window_size.x, Global.window_size.y, Global.bFullScreen && shown ? monitor : nullptr, true, false);
if (mainwindow == nullptr)
diff --git a/application/driverhints.cpp b/application/driverhints.cpp
index ae39ede7a..0c6f02cc8 100644
--- a/application/driverhints.cpp
+++ b/application/driverhints.cpp
@@ -326,6 +326,14 @@ TController::cue_action( driver_hint const Action, float const Actionparameter )
case driver_hint::converteron: {
if( AIControllFlag ) {
mvOccupied->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
+ pVehicle->for_each(
+ coupling::control,
+ []( TDynamicObject * Vehicle ) {
+ auto *vehicle { Vehicle->MoverParameters };
+ if( vehicle->LineContactorsHeldByLocalConverterSwitch() ) {
+ vehicle->ConverterAllowLocal = true; } } );
}
remove_hint( driver_hint::converteroff );
hint(
diff --git a/application/drivermode.cpp b/application/drivermode.cpp
index 71a343d6b..efaba691b 100644
--- a/application/drivermode.cpp
+++ b/application/drivermode.cpp
@@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/.
#include "simulation/simulationtime.h"
#include "simulation/simulationenvironment.h"
#include "simulation/simulationtest.h"
+#include "simulation/blackboxrecorder.h"
#include "scene/scene.h"
#include "rendering/lightarray.h"
#include "rendering/particles.h"
@@ -160,6 +161,30 @@ bool driver_mode::init()
}
// mode-specific update of simulation data. returns: false on error, true otherwise
+namespace {
+
+// the camera as the black box tells it: where it is and where it looks, as the heading of a vehicle
+blackbox::camera_state blackbox_camera(TCamera const &Camera, std::uint8_t const Mode, int const View) {
+ blackbox::camera_state state;
+ state.mode = Mode;
+ state.view = static_cast(View);
+ state.position = Camera.Pos;
+ state.pitch = Camera.Angle.x;
+ if (Camera.m_owner != nullptr && false == DebugCameraFlag) {
+ // it looks at a point, then turns by its yaw from there
+ auto const where{Camera.LookAt - Camera.Pos};
+ state.heading = static_cast(std::atan2(where.x, where.z)) + Camera.Angle.y;
+ }
+ else {
+ // the yaw alone: 0 looks towards -z
+ state.heading = static_cast(std::atan2(-std::sin(Camera.Angle.y), -std::cos(Camera.Angle.y)));
+ }
+ state.heading = std::remainder(state.heading, 2.0f * glm::pi());
+ return state;
+}
+
+} // namespace
+
bool driver_mode::update()
{
@@ -318,6 +343,17 @@ bool driver_mode::update()
Timer::subsystem.sim_lights.start();
simulation::Lights.update();
Timer::subsystem.sim_lights.stop();
+ {
+ // where the user looks from, for the black box
+ auto const &camera{DebugCameraFlag ? DebugCamera : Camera};
+ auto const mode{DebugCameraFlag ? blackbox::camera_modes::debug :
+ false == FreeFlyModeFlag ? blackbox::camera_modes::cab :
+ m_externalview ? blackbox::camera_modes::external :
+ blackbox::camera_modes::free};
+ simulation::Blackbox.camera(blackbox_camera(camera, mode, mode == blackbox::camera_modes::external ? m_externalviewmode : 0),
+ DebugCameraFlag ? nullptr : camera.m_owner);
+ }
+ simulation::Blackbox.update(deltatime);
if (Global.test.enabled && simulation::is_ready)
{
diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp
index 3b4e6c9c2..91fb2ff62 100644
--- a/application/driveruipanels.cpp
+++ b/application/driveruipanels.cpp
@@ -40,6 +40,26 @@ http://mozilla.org/MPL/2.0/.
#include "utilities/uart.h"
#endif
+#include
+
+namespace {
+
+// how close to a broken coupler the camera has to be for the driving aid to offer its repair [m]
+constexpr float coupler_repair_radius { 5.f };
+
+// the broken coupler nearest to the camera, within reach: the vehicle and its end, or no vehicle
+std::pair broken_coupler_nearby( glm::dvec3 const &Camera ) {
+ auto const *vehicle { std::get( simulation::Region->find_vehicle( Camera, coupler_repair_radius, false, true ) ) };
+ if( vehicle == nullptr || vehicle->MoverParameters == nullptr ) { return { nullptr, end::front }; }
+ auto const front { glm::distance( vehicle->CouplerPosition( end::front ), Camera ) };
+ auto const rear { glm::distance( vehicle->CouplerPosition( end::rear ), Camera ) };
+ auto const nearest { front <= rear ? end::front : end::rear };
+ if( std::min( front, rear ) > coupler_repair_radius || false == vehicle->MoverParameters->Couplers[ nearest ].broken ) { return { nullptr, end::front }; }
+ return { vehicle, nearest };
+}
+
+} // namespace
+
void
drivingaid_panel::update() {
@@ -47,6 +67,8 @@ drivingaid_panel::update() {
text_lines.clear();
+ std::tie( m_brokenvehicle, m_brokenend ) = broken_coupler_nearby( Global.pCamera.Pos );
+
auto const *train { simulation::Train };
auto const *controlled { ( train ? train->Dynamic() : nullptr ) };
@@ -72,53 +94,7 @@ drivingaid_panel::update() {
}
// next speed limit
auto const speedlimit { static_cast( owner->VelDesired ) };
- auto nextspeedlimit { speedlimit };
- auto nextspeedlimitdistance { std::numeric_limits::max() };
- if( speedlimit != 0 ) { // if we aren't allowed to move then any next speed limit is irrelevant
- // nie przekraczać rozkladowej
- auto const schedulespeedlimit { (
- (owner->OrderCurrentGet() & (Obey_train | Bank)) != 0 && owner->TrainParams.TTVmax > 0.0 ? static_cast( owner->TrainParams.TTVmax ) :
- (owner->OrderCurrentGet() & (Obey_train | Bank)) == 0 ? static_cast( owner->fShuntVelocity ) :
- -1 ) };
- // first take note of any speed change which should occur after passing potential current speed limit
- if( owner->VelLimitLastDist.second > 0 ) {
- nextspeedlimit = min_speed( schedulespeedlimit, static_cast( owner->VelLimitLastDist.first ) );
- nextspeedlimitdistance = owner->VelLimitLastDist.second;
- }
- // then take into account speed change ahead, compare it with speed after potentially clearing last limit
- // lower of these two takes priority; otherwise limit lasts at least until potential last limit is cleared
- auto const noactivespeedlimit { owner->VelLimitLastDist.second < 0 };
- if( auto const speedatproximitydistance { min_speed( schedulespeedlimit, static_cast( owner->VelNext ) ) }; speedatproximitydistance == nextspeedlimit ) {
- if( noactivespeedlimit ) {
- nextspeedlimit = speedatproximitydistance;
- nextspeedlimitdistance = owner->ActualProximityDist;
- }
- }
- else if( speedatproximitydistance < nextspeedlimit ) {
- // if the speed limit ahead is more strict than our current limit, it's important enough to report
- if( speedatproximitydistance < owner->VelDesired ) {
- nextspeedlimit = speedatproximitydistance;
- nextspeedlimitdistance = owner->ActualProximityDist;
- }
- // otherwise report it only if it's located after our current (lower) limit ends
- else if( owner->ActualProximityDist > nextspeedlimitdistance ) {
- nextspeedlimit = speedatproximitydistance;
- nextspeedlimitdistance = owner->ActualProximityDist;
- }
- }
- else if( noactivespeedlimit ) { // implicit proximity > last, report only if last limit isn't present
- nextspeedlimit = speedatproximitydistance;
- nextspeedlimitdistance = owner->ActualProximityDist;
- }
- // HACK: if our current speed limit extends beyond our scan range don't display potentially misleading information about its length
- if( nextspeedlimitdistance >= EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE ) {
- nextspeedlimit = speedlimit;
- }
- // HACK: hide next speed limit if the 'limit' is a vehicle in front of us
- else if( owner->ActualProximityDist == std::abs( owner->TrackObstacle() ) ) {
- nextspeedlimit = speedlimit;
- }
- }
+ auto const [ nextspeedlimit, nextspeedlimitdistance ] { owner->next_speed_limit() };
std::string nextspeedlimittext;
if( nextspeedlimit != speedlimit ) {
std::snprintf(
@@ -223,6 +199,12 @@ drivingaid_panel::render_contents() {
}
}
+ // only the coupler the camera is next to, and the one of the vehicle it was coupled with
+ if( m_brokenvehicle != nullptr && ImGui::Button( STR_C( "Repair coupler" ) ) ) {
+ command_relay commandrelay;
+ commandrelay.post( user_command::repaircoupler, m_brokenend, 0.0, GLFW_PRESS, 0, glm::vec3( 0.0f ), &m_brokenvehicle->name() );
+ }
+
ui_panel::render_contents();
}
@@ -546,6 +528,7 @@ void debug_panel::update()
m_powergridlines.clear();
m_cameralines.clear();
m_rendererlines.clear();
+ m_couplerlines.clear();
#ifdef WITH_UART
m_uartlines.clear();
#endif
@@ -559,6 +542,7 @@ void debug_panel::update()
update_section_powergrid( m_powergridlines );
update_section_camera( m_cameralines );
update_section_renderer( m_rendererlines );
+ update_section_coupler( m_couplerlines );
#ifdef WITH_UART
update_section_uart(m_uartlines);
#endif
@@ -608,6 +592,7 @@ debug_panel::render() {
command_relay commandrelay;
commandrelay.post(user_command::resetconsist, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &m_input.vehicle->name());
}
+ render_section_coupler();
render_section( "Vehicle Engine", m_enginelines );
render_section( "Vehicle AI", m_ailines );
render_section( "Vehicle Scan Table", m_scantablelines );
@@ -1510,6 +1495,172 @@ debug_panel::update_section_renderer( std::vector &Output ) {
}
+namespace {
+
+// how far from the camera a coupler shows in the coupler section [m]
+constexpr float coupler_pick_radius { 10.f };
+
+std::string_view coupler_type_name( TCouplerType const Type ) {
+ switch( Type ) {
+ case TCouplerType::Articulated: { return "articulated"; }
+ case TCouplerType::Bare: { return "bare"; }
+ case TCouplerType::Chain: { return "chain"; }
+ case TCouplerType::Screw: { return "screw"; }
+ case TCouplerType::Automatic: { return "automatic"; }
+ default: { return "none"; }
+ }
+}
+
+// the couplerphysics setting of eu07.ini
+std::string_view coupler_physics_setting() {
+ if( Global.coupler_physics_all ) { return "all"; }
+ return Global.coupler_physics ? "yes" : "no";
+}
+
+std::string_view coupler_stop_name( int const Stop ) {
+ if( Stop > 0 ) { return "draw gear solid"; }
+ if( Stop < 0 ) { return "buffers solid"; }
+ return "none";
+}
+
+// a value shown in the Scale of its unit (1000 for kN, 0.001 for mm), dragged within Min and Max of that unit
+bool edit_value( char const *Label, double &Value, double const Scale, double const Min, double const Max, char const *Format ) {
+ auto shown { Value / Scale };
+ if( false == ImGui::DragScalar( Label, ImGuiDataType_Double, &shown, static_cast( ( Max - Min ) / 1000.0 ), &Min, &Max, Format ) ) {
+ return false;
+ }
+ Value = std::clamp( shown, Min, Max ) * Scale;
+ return true;
+}
+
+bool edit_spring( char const *Name, coupler_physics::spring_curve &Curve, double &Unloading ) {
+ ImGui::PushID( Name );
+ ImGui::TextUnformatted( Name );
+ auto changed { edit_value( "Stiffness [kN/m]", Curve.stiffness, 1000.0, 100.0, 50000.0, "%.0f" ) };
+ changed = edit_value( "Travel [mm]", Curve.travel, 0.001, 5.0, 300.0, "%.0f" ) || changed;
+ changed = edit_value( "Progression", Curve.progression, 1.0, 0.0, 0.9, "%.2f" ) || changed;
+ changed = edit_value( "Unloading ratio", Unloading, 1.0, 0.05, 1.0, "%.2f" ) || changed;
+ ImGui::Text( "End force: %.0f kN", Curve.end_force() / 1000.0 );
+ ImGui::PopID();
+ return changed;
+}
+
+bool edit_link( coupler_physics::end_parameters &Parameters ) {
+ auto &link { Parameters.link };
+ ImGui::PushID( "link" );
+ ImGui::TextUnformatted( "Link" );
+ auto changed { ImGui::Checkbox( "Breakable", &link.breakable ) };
+ changed = edit_value( "Ultimate force [kN]", link.ultimate, 1000.0, 10.0, 5000.0, "%.0f" ) || changed;
+ changed = edit_value( "Yield force [kN]", link.yield, 1000.0, 10.0, 5000.0, "%.0f" ) || changed;
+ link.yield = std::min( link.yield, link.ultimate );
+ // the permanent stretch at which the link breaks, which is what the hardening gives
+ auto stretch { ( link.ultimate - link.yield ) / link.hardening };
+ if( edit_value( "Stretch to break [mm]", stretch, 0.001, 1.0, 200.0, "%.1f" ) ) {
+ link.hardening = std::max( ( link.ultimate - link.yield ) / stretch, 1.0 );
+ changed = true;
+ }
+ changed = edit_value( "Link stiffness [kN/m]", Parameters.link_stiffness, 1000.0, 1000.0, 2000000.0, "%.0f" ) || changed;
+ changed = edit_value( "Buffers crush force [kN]", Parameters.crush_force, 1000.0, 100.0, 10000.0, "%.0f" ) || changed;
+ changed = edit_value( "Restitution of a solid hit", Parameters.solid_restitution, 1.0, 0.05, 0.95, "%.2f" ) || changed;
+ ImGui::PopID();
+ return changed;
+}
+
+bool edit_coupler_parameters( coupler_physics::end_parameters &Parameters ) {
+ auto changed { edit_value( "Slack [mm]", Parameters.slack, 0.001, -100.0, 300.0, "%.1f" ) };
+ changed = edit_value( "Damping [kN s/m]", Parameters.damping, 1000.0, 0.0, 1000.0, "%.1f" ) || changed;
+ changed = edit_spring( "Buffers", Parameters.buffers, Parameters.buffers_unloading ) || changed;
+ changed = edit_spring( "Draw gear", Parameters.draw_gear, Parameters.draw_gear_unloading ) || changed;
+ changed = edit_link( Parameters ) || changed;
+ return changed;
+}
+
+} // namespace
+
+void
+debug_panel::update_section_coupler( std::vector &Output ) {
+
+ m_coupler = {};
+ if( m_input.camera == nullptr ) { return; }
+ auto const &camera { m_input.camera->Pos };
+ auto const *vehicle { std::get( simulation::Region->find_vehicle( camera, coupler_pick_radius, false, true ) ) };
+ if( vehicle == nullptr || vehicle->MoverParameters == nullptr ) {
+ Output.emplace_back( std::format( "No coupler within {:.0f} m of the camera", coupler_pick_radius ), Global.UITextColor );
+ return;
+ }
+ auto const nearerfront { glm::distance( vehicle->CouplerPosition( end::front ), camera ) <= glm::distance( vehicle->CouplerPosition( end::rear ), camera ) };
+ m_coupler = { vehicle, nearerfront ? end::front : end::rear };
+
+ auto const &mover { *vehicle->MoverParameters };
+ auto const &coupler { mover.Couplers[ m_coupler.end ] };
+ auto const &neighbour { mover.Neighbours[ m_coupler.end ] };
+ auto const &state { coupler.physics_state };
+
+ Output.emplace_back(
+ std::format( "{}, {} end, {} coupler{}", vehicle->name(), nearerfront ? "front" : "rear", coupler_type_name( coupler.type() ), coupler.has_adapter() ? " (adapter)" : "" ),
+ Global.UITextColor );
+ Output.emplace_back(
+ std::format(
+ "Model: {} (couplerphysics {}, vehicle {}covered), crash damage {}",
+ mover.coupler_physics_at( m_coupler.end ) ? "physical" : "legacy",
+ coupler_physics_setting(),
+ mover.CouplerPhysics ? "" : "not ",
+ Global.crash_damage ? "on" : "off" ),
+ Global.UITextColor );
+ if( neighbour.vehicle != nullptr ) {
+ Output.emplace_back(
+ std::format( "Neighbour: {} ({} end), coupling [{}], gap {:.1f} mm", neighbour.vehicle->name(), neighbour.vehicle_end == end::front ? "front" : "rear", coupler.CouplingFlag, neighbour.distance * 1000.0 ),
+ Global.UITextColor );
+ }
+ else {
+ Output.emplace_back( "Neighbour: none", Global.UITextColor );
+ }
+ Output.emplace_back( std::format( "Force: {:.1f} kN", coupler.CForce / 1000.0 ), Global.UITextColor );
+ Output.emplace_back(
+ std::format( "Draw gear: {:.1f} mm, {:.1f} kN Buffers: {:.1f} mm, {:.1f} kN", state.draw_gear.deflection * 1000.0, state.draw_gear.force / 1000.0, state.buffers.deflection * 1000.0, state.buffers.force / 1000.0 ),
+ Global.UITextColor );
+ Output.emplace_back(
+ std::format( "Stretch: {:.1f} mm, stop: {}, overloaded for {:.1f} s", state.elongation * 1000.0, coupler_stop_name( state.stop ), coupler.stretch_duration ),
+ Global.UITextColor );
+ if( coupler.broken ) {
+ Output.emplace_back( "Coupler broken (repair it in the driving aid, F1)", glm::vec4( 1.f, 0.25f, 0.25f, 1.f ) );
+ }
+}
+
+bool
+debug_panel::render_section_coupler() {
+
+ if( false == render_section( "Coupler", m_couplerlines ) ) { return false; }
+ // the parameters to try out, in the debug mode, on the simulation itself
+ if( false == DebugModeFlag || m_coupler.vehicle == nullptr || Application.is_client() ) { return true; }
+
+ ImGui::Separator();
+ ImGui::Checkbox( "Physical coupler model", &Global.coupler_physics );
+ ImGui::Checkbox( "Physical model for every train", &Global.coupler_physics_all );
+ ImGui::Checkbox( "Crash damage", &Global.crash_damage );
+ ImGui::Checkbox( "Apply to the other end of the pair too", &m_couplerbothends );
+
+ auto &mover { *m_coupler.vehicle->MoverParameters };
+ auto &coupler { mover.Couplers[ m_coupler.end ] };
+ auto const &neighbour { mover.Neighbours[ m_coupler.end ] };
+ auto *othercoupler { neighbour.vehicle != nullptr ? &neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] : nullptr };
+
+ if( auto parameters { coupler.physics }; edit_coupler_parameters( parameters ) ) {
+ coupler.physics = parameters;
+ if( m_couplerbothends && othercoupler != nullptr ) {
+ othercoupler->physics = parameters;
+ }
+ }
+ if( ImGui::Button( "Reset the stretch of the coupling" ) ) {
+ // both vehicles keep the state of the pair alike
+ coupler.physics_state.elongation = 0.0;
+ if( othercoupler != nullptr ) {
+ othercoupler->physics_state.elongation = 0.0;
+ }
+ }
+ return true;
+}
+
bool
debug_panel::render_section( std::string const &Header, std::vector const &Lines ) {
diff --git a/application/driveruipanels.h b/application/driveruipanels.h
index ed971f9ff..0e8b6917e 100644
--- a/application/driveruipanels.h
+++ b/application/driveruipanels.h
@@ -26,6 +26,9 @@ public:
private:
// members
std::array m_buffer;
+ // the broken coupler next to the camera, which the panel offers to repair: the vehicle and its end
+ TDynamicObject const *m_brokenvehicle { nullptr };
+ int m_brokenend { 0 };
};
class timetable_panel : public ui_expandable_panel {
@@ -90,6 +93,8 @@ private:
void update_section_powergrid( std::vector &Output ) const;
void update_section_camera( std::vector &Output ) const;
void update_section_renderer( std::vector &Output );
+ // the coupler nearest to the camera, and the state of its coupling
+ void update_section_coupler( std::vector &Output );
#ifdef WITH_UART
void update_section_uart( std::vector &Output ) const;
#endif
@@ -102,6 +107,8 @@ private:
bool render_section_scenario();
bool render_section_eventqueue();
bool render_section_renderer();
+ // the coupler section, with the parameters of the physical model to try out in the debug mode
+ bool render_section_coupler();
bool render_section_settings() const;
bool render_section_developer() const;
// members
@@ -119,6 +126,14 @@ private:
std::vector m_rendererlines;
std::vector m_renderersections; // the data of the renderer, each part under a header of its own
std::vector m_uartlines;
+ std::vector m_couplerlines;
+ // the coupler nearest to the camera
+ struct coupler_pick {
+ TDynamicObject const *vehicle { nullptr };
+ int end { 0 };
+ };
+ coupler_pick m_coupler;
+ bool m_couplerbothends { true }; // changes to the parameters apply to the end of the other vehicle of the pair too
double last_time = std::numeric_limits::quiet_NaN();
diff --git a/application/editormode.cpp b/application/editormode.cpp
index 61f1405fc..93498a58d 100644
--- a/application/editormode.cpp
+++ b/application/editormode.cpp
@@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/.
#include "stdafx.h"
#include "world/TrackSleepers.h"
#include
+#include
#include
#include
#include
@@ -26,6 +27,7 @@ extern char **environ;
#include "application/editorprojection.h"
#include "application/application.h"
+#include "editor/editorKilometrage.hpp"
#include "editor/editorSettings.hpp"
#include "editor/editorModelSets.hpp"
#include "editor/editorTrackPresets.hpp"
@@ -44,6 +46,7 @@ extern char **environ;
#include "simulation/simulationtime.h"
#include "simulation/simulationenvironment.h"
#include "widgets/weatherpanel.h"
+#include "simulation/blackboxrecorder.h"
#include "utilities/Timer.h"
#include "Console.h"
#include "rendering/renderer.h"
@@ -702,7 +705,7 @@ bool editor_mode::init()
auto const &model{EditorSettings.terrain_model()};
m_nmt_state.grow = EditorSettings.terrain_while_laying();
m_nmt_state.band = std::clamp(model.band, 50.0, 3000.0);
- m_nmt_state.shape = model.shape;
+ // the formation and the slopes are always made along the tracks: the switch of them is gone, a setting left off by it isn't kept
m_nmt_state.follow = model.follow;
m_terrain_add_count = std::clamp(model.around, 1, 8);
EditorModelSets.load();
@@ -753,6 +756,8 @@ void editor_mode::start_focus(scene::basic_node *node, double duration)
void editor_mode::fly_to(glm::dvec3 const &Target, glm::dvec3 const &Look, double const Distance, double const Duration)
{
+ // the camera flown off somewhere leaves the track it rode along
+ m_ride.leave();
m_focus_start_pos = Camera.Pos;
m_focus_start_angle = Camera.Angle;
m_focus_target_pos = Target - Look * Distance;
@@ -1397,6 +1402,7 @@ bool editor_mode::update()
Global.editor_tracks = (current_work_area() == work_area::tracks);
selftest_step();
steps.step("selftest");
+ thumbnails_trim();
// the drives of the switches go to the tips of their blades once, as the templates of the scenery are known
if (false == m_drives_checked)
{
@@ -1528,6 +1534,9 @@ bool editor_mode::update()
{
m_include_gesture = false;
}
+ // the gizmo let go of a signal while it wasn't drawn
+ if (false == m_gizmo_using)
+ signal_gizmo_end();
// models replaced after changes of includes are destroyed once the renderer can't have them among its pick candidates
for (auto &retired : m_retired)
{
@@ -1591,6 +1600,7 @@ bool editor_mode::update()
render_gizmo();
// the tools, the gizmo modes and the axes over the 3d view
render_viewport_overlays();
+ m_ride.draw_hud();
render_track_inspector();
steps.step("inspector");
@@ -1620,7 +1630,7 @@ bool editor_mode::update()
draw_switch_slide();
if (m_track_tab == track_tab::turntable)
draw_turntable_overlay();
- if (m_track_tab == track_tab::srk)
+ if (m_track_tab == track_tab::signals)
{
signal_refresh();
signal_move_update();
@@ -1658,6 +1668,12 @@ bool editor_mode::update()
steps.step("speed");
m_joints.update();
steps.step("joints");
+ if (m_nmt_state.grade_lines_dirty)
+ {
+ m_nmt_state.grade_lines_dirty = false;
+ grade_lines_store();
+ }
+ m_nmt_state.grade_line_replaced.clear();
m_srk.update();
kilometrage::follow(m_track_edits);
m_km.update();
@@ -1665,6 +1681,7 @@ bool editor_mode::update()
draw_track_hints();
draw_empty_scenery_hint();
draw_profile_overlay();
+ draw_grade_line_pick();
draw_infra_overlay();
m_speed.draw_overlay();
m_joints.draw_overlay();
@@ -1681,6 +1698,7 @@ bool editor_mode::update()
}
m_gauge.update();
m_gauge.render_windows();
+ m_minimap.render_windows();
// roads: trajectories of the lanes, and the tools of the road window
update_road_tool();
@@ -1704,6 +1722,9 @@ bool editor_mode::update()
render_first_steps();
render_nmt_prompt();
render_nmt_banner();
+ render_nmt_buried();
+ render_empty_scenery_hint();
+ render_outside_area_hint();
render_switch_designer();
render_environment_window();
if (m_terrain_open)
@@ -1808,6 +1829,12 @@ void editor_mode::render_terrain_ui()
ImGui::SetTooltip("%s", STR_C("Kept in the folder terrain// and written there with the scenery (Ctrl+S)"));
return;
}
+ // the real terrain first, open: the tracks put onto it from there
+ if (nmt_busy())
+ ImGui::SetNextItemOpen(true);
+ if (ImGui::CollapsingHeader(STR_C("Terrain model (NMT)"), ImGuiTreeNodeFlags_DefaultOpen))
+ render_nmt_ui();
+
// the tools are chosen in the toolbar, here are their settings
if (ImGui::CollapsingHeader(STR_C("Chunks"), m_terrain_tool == terrain_tool::chunks ? ImGuiTreeNodeFlags_DefaultOpen : 0))
{
@@ -1843,11 +1870,6 @@ void editor_mode::render_terrain_ui()
}
}
- if (nmt_busy())
- ImGui::SetNextItemOpen(true);
- if (ImGui::CollapsingHeader(STR_C("Terrain model (NMT)")))
- render_nmt_ui();
-
if (ImGui::CollapsingHeader(STR_C("Chunk resolution"), m_terrain_tool == terrain_tool::spacing ? ImGuiTreeNodeFlags_DefaultOpen : 0))
{
// chunks removed since are no longer selected
@@ -1983,9 +2005,7 @@ void editor_mode::render_terrain_ui()
ImGui::SetTooltip("%s", STR_C("Angle the textures of the chosen material are turned by, on every chunk painted with it.\n"
"Ctrl+click to type it. To have the material turned in one place only, fill it there with an angle of its own."));
}
- ImGui::SetNextItemWidth(160.0f);
- ImGui::InputText(STR_C("Material"), m_terrain_material, IM_ARRAYSIZE(m_terrain_material));
- material_drop(m_terrain_material, IM_ARRAYSIZE(m_terrain_material));
+ texture_field(STR_C("Material"), 160.0f, m_terrain_material, IM_ARRAYSIZE(m_terrain_material), terrain_texture_offer(nullptr));
ImGui::SameLine();
if (ImGui::Button(STR_C("Add to the palette")) && m_terrain_material[0] != '\0')
m_terrain_layer = m_streamer.layer(m_terrain_material, m_terrain_material_size);
@@ -2083,11 +2103,9 @@ void editor_mode::render_terrain_ui()
ImGui::SetNextItemWidth(120.0f);
if (ImGui::DragFloat(STR_C("Level (m)"), &m_water_level, 0.01f, -1000.0f, 5000.0f, "%.2f"))
m_water_level_edited = true;
- ImGui::SetNextItemWidth(160.0f);
- ImGui::InputText(STR_C("Material##water"), m_water_material, IM_ARRAYSIZE(m_water_material));
- material_drop(m_water_material, IM_ARRAYSIZE(m_water_material));
+ texture_field(STR_C("Material##water"), 160.0f, m_water_material, IM_ARRAYSIZE(m_water_material), terrain_texture_offer(STR_C("The default water material")));
if (ImGui::IsItemHovered())
- ImGui::SetTooltip(STR_C("Empty: %s, the water material of the terrain"), m_streamer.manifest().water_material.c_str());
+ ImGui::SetTooltip(STR_C("The default one: %s, the water material of the terrain"), m_streamer.manifest().water_material.c_str());
ImGui::BeginDisabled(m_water_points.size() < 3);
if (ImGui::Button(STR_C("Make the water")))
{
@@ -2157,12 +2175,9 @@ void editor_mode::render_terrain_ui()
m_water_material_of = m_water_selected;
}
bool retexture = false;
- ImGui::SetNextItemWidth(160.0f);
- ImGui::InputText(STR_C("Material of the chosen"), m_water_selected_material, IM_ARRAYSIZE(m_water_selected_material));
- retexture |= ImGui::IsItemDeactivatedAfterEdit();
- retexture |= material_drop(m_water_selected_material, IM_ARRAYSIZE(m_water_selected_material));
+ retexture |= texture_field(STR_C("Material of the chosen"), 160.0f, m_water_selected_material, IM_ARRAYSIZE(m_water_selected_material), terrain_texture_offer(STR_C("The default water material")));
if (ImGui::IsItemHovered())
- ImGui::SetTooltip(STR_C("A material or a texture (drag one from the texture browser).\nEmpty: %s, the water material of the terrain"), m_streamer.manifest().water_material.c_str());
+ ImGui::SetTooltip(STR_C("Chosen from the textures, or dragged from the texture browser.\nThe default one: %s, the water material of the terrain"), m_streamer.manifest().water_material.c_str());
ImGui::SetNextItemWidth(120.0f);
ImGui::DragFloat(STR_C("Texture repeats every (m)##water"), &m_water_selected_size, 0.1f, 0.0f, 500.0f, "%.1f");
m_water_selected_size = std::max(0.0f, m_water_selected_size);
@@ -2188,17 +2203,12 @@ void editor_mode::render_terrain_ui()
m_water_material_of = -1;
}
// the material of the bodies of water which don't name their own
- if (false == m_water_default_edited)
- std::snprintf(m_water_default_material, sizeof(m_water_default_material), "%s", m_streamer.manifest().water_material.c_str());
- ImGui::SetNextItemWidth(160.0f);
- ImGui::InputText(STR_C("Default water material"), m_water_default_material, IM_ARRAYSIZE(m_water_default_material));
- m_water_default_edited = ImGui::IsItemActive();
- bool redefault = ImGui::IsItemDeactivatedAfterEdit();
- redefault |= material_drop(m_water_default_material, IM_ARRAYSIZE(m_water_default_material));
+ auto defaultmaterial{m_streamer.manifest().water_material};
+ auto const redefault{texture_field(STR_C("Default water material"), 160.0f, defaultmaterial, terrain_texture_offer(nullptr))};
if (ImGui::IsItemHovered())
ImGui::SetTooltip("%s", STR_C("Material of the bodies of water which don't name their own"));
if (redefault)
- m_streamer.water_material(m_water_default_material);
+ m_streamer.water_material(defaultmaterial);
}
if (ImGui::CollapsingHeader(STR_C("Modifiers")))
@@ -2266,9 +2276,9 @@ void editor_mode::draw_terrain_overlay()
return;
screen_projection const projection;
auto *drawlist = ImGui::GetBackgroundDrawList();
- glm::dvec3 const offset = GfxRenderer->Mouse_Position();
- bool const hovering = glm::length(offset) > 1e-3 && false == ImGui::GetIO().WantCaptureMouse;
- glm::dvec3 const cursor = Camera.Pos + offset;
+ // the cursor where a click would put the point: the ground along the ray through the cursor in this frame
+ glm::dvec3 cursor{Camera.Pos};
+ bool const hovering = false == ImGui::GetIO().WantCaptureMouse && cursor_on_ground(cursor);
auto const ground = [&](double const X, double const Z, double const Fallback) {
double height;
return m_streamer.height_at(X, Z, height) ? height : Fallback;
@@ -2283,12 +2293,12 @@ void editor_mode::draw_terrain_overlay()
}
};
- // the holes and the grass are aimed at the ground itself, also over an opening and behind the blades
+ // the brush aimed at the ground itself along the ray through the cursor
glm::dvec3 brushcentre = cursor;
- bool const onground = (m_terrain_tool == terrain_tool::holes || m_terrain_tool == terrain_tool::grass) && false == ImGui::GetIO().WantCaptureMouse && terrain_cursor(brushcentre);
- if (terrain_brush() && (hovering || onground))
+ bool const onground = false == ImGui::GetIO().WantCaptureMouse && terrain_cursor(brushcentre);
+ if (terrain_brush() && onground)
{
- auto const cursor = onground ? brushcentre : Camera.Pos + offset;
+ auto const cursor = brushcentre;
std::vector circle;
for (int i = 0; i < 64; ++i)
{
@@ -2479,7 +2489,7 @@ void editor_mode::load_orthophoto_settings()
m_orthophoto.settings(config);
m_orthophoto_origin_edit = {config.north, config.east};
// the area the imagery and the terrain model are downloaded in, none in a scenery which has none
- m_orthophoto_area_mark = scene::Layers.empty() ? std::vector{} : scene::Layers.marked(scene::layer_handle{1}, "//$a");
+ m_orthophoto_area_mark = scene::Layers.empty() ? std::vector{} : scene::Layers.marked(scene::layer_handle{1}, "//$z");
m_orthophoto.area(editor_orthophoto::read_area(m_orthophoto_area_mark));
if (false == m_orthophoto.area().empty())
WriteLog(format("Editor: the download area of the scenery, %zu points, %d tiles of the orthophoto", m_orthophoto.area().size(), m_orthophoto.stats().area_tiles));
@@ -2624,17 +2634,54 @@ void editor_mode::render_orthophoto_ui()
if (ImGui::TreeNode(STR_C("More settings")))
{
- if (ImGui::Checkbox(STR_C("Fit to terrain"), &config.drape))
+ // one choice of three, what it means under it: drawn over the view (laid on the ground, where there's none at the height), a
+ // surface of the scene on the ground, or a flat sheet in the scene; flat over the view says nothing more than on the ground
+ enum class look
{
- changed = true;
- persist = true;
+ overlay,
+ ground,
+ sheet
+ };
+ auto const current{false == config.in_scene ? look::overlay : config.drape ? look::ground : look::sheet};
+ auto const choice = [&](char const *Label, look const Look) {
+ if (ImGui::RadioButton(Label, current == Look) && current != Look)
+ {
+ config.in_scene = Look != look::overlay;
+ config.drape = Look != look::sheet;
+ changed = true;
+ persist = true;
+ }
+ };
+ auto const explain = [](char const *Text) {
+ ImGui::Indent();
+ ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + 360.0f);
+ ImGui::TextDisabled("%s", Text);
+ ImGui::PopTextWrapPos();
+ ImGui::Unindent();
+ };
+
+ ImGui::TextUnformatted(STR_C("Show the photos"));
+ choice(STR_C("Over the view"), look::overlay);
+ choice(STR_C("On the terrain, in the scene"), look::ground);
+ choice(STR_C("A flat sheet in the scene"), look::sheet);
+ switch (current)
+ {
+ case look::overlay:
+ explain(STR_C("The photos are drawn over the whole view, over the tracks and models as well: lower the opacity to see "
+ "what's under them. The quickest way to compare the scenery with the map."));
+ break;
+ case look::ground:
+ explain(STR_C("The photos lie on the terrain as its surface: tracks and models standing on them cover them, the scene lights "
+ "them, and fully opaque the mouse places objects on them as on the ground."));
+ break;
+ case look::sheet:
+ explain(STR_C("One flat sheet at the height below, in the scene: for a scenery with no terrain yet. Where there is "
+ "terrain, it cuts through the sheet."));
+ break;
}
- if (ImGui::IsItemHovered())
- ImGui::SetTooltip(STR_C("Lays the imagery onto the ground geometry (terrain shapes, terrain tile models, heightmap terrain).\n"
- "Places without any ground use the height below."));
+
if (config.drape)
{
- ImGui::SameLine();
if (ImGui::Button(STR_C("Refit")))
{
// the ground was edited: what's kept of it has to go as well
@@ -2645,33 +2692,22 @@ void editor_mode::render_orthophoto_ui()
layer->refit();
}
if (ImGui::IsItemHovered())
- ImGui::SetTooltip(STR_C("Samples the ground again, after it was edited"));
+ ImGui::SetTooltip("%s", STR_C("Samples the ground again, after it was edited"));
+ // the lift only matters where the scene can cover the photos
+ if (config.in_scene)
+ {
+ ImGui::SetNextItemWidth(160.0f);
+ changed |= ImGui::DragFloat(STR_C("Lift above ground (m)"), &config.lift, 0.01f, 0.0f, 50.0f, "%.2f");
+ persist |= ImGui::IsItemDeactivatedAfterEdit();
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("%s", STR_C("Raises the photos above the ground.\n"
+ "Whatever is lower than this, the rails and the sleepers too, ends up under them: keep it small."));
+ }
}
-
- begin_disabled(!config.drape);
ImGui::SetNextItemWidth(160.0f);
- changed |= ImGui::DragFloat(STR_C("Lift above ground (m)"), &config.lift, 0.01f, 0.0f, 50.0f, "%.2f");
+ changed |= ImGui::DragFloat(config.drape ? STR_C("Height where there's no ground (m)") : STR_C("Height (m)"), &config.height, 0.1f, -1000.0f, 3000.0f, "%.2f");
persist |= ImGui::IsItemDeactivatedAfterEdit();
- end_disabled(!config.drape);
- if (ImGui::IsItemHovered())
- ImGui::SetTooltip(STR_C("Raises the fitted imagery above the ground. Keep it below the objects you want to see:\n"
- "in the scene everything lower than this ends up under the imagery."));
-
- begin_disabled(config.drape);
- ImGui::SetNextItemWidth(160.0f);
- changed |= ImGui::DragFloat(STR_C("Height (m)"), &config.height, 0.1f, -1000.0f, 3000.0f, "%.2f");
- persist |= ImGui::IsItemDeactivatedAfterEdit();
- end_disabled(config.drape);
-
- if (ImGui::Checkbox(STR_C("Covered by objects and terrain"), &config.in_scene))
- {
- changed = true;
- persist = true;
- }
- if (ImGui::IsItemHovered())
- ImGui::SetTooltip(STR_C("Draws the imagery as part of the scene, so tracks, models and terrain in front of it hide it.\n"
- "It is lit like the scene. Fully opaque, mouse placement lands on it as on any surface;\n"
- "translucent, it doesn't catch the mouse."));
+ ImGui::Spacing();
ImGui::SetNextItemWidth(160.0f);
changed |= ImGui::SliderFloat(STR_C("Opacity"), &config.opacity, 0.0f, 1.0f, "%.2f");
@@ -2775,7 +2811,8 @@ void editor_mode::draw_ortho_compass() const
ImGuiIO const &io = ImGui::GetIO();
float const radius{36.0f};
float const margin{16.0f};
- ImVec2 const center{io.DisplaySize.x - margin - radius, margin + radius};
+ // in the corner of the view, where the buttons of the toolbar and the hints along its bottom aren't
+ ImVec2 const center{editor_ui::view_max().x - margin - radius - 14.0f, editor_ui::view_max().y - margin - radius - 54.0f};
auto *drawlist{ImGui::GetForegroundDrawList()};
drawlist->AddCircleFilled(center, radius + 14.0f, IM_COL32(0, 0, 0, 180), 48);
drawlist->AddCircle(center, radius - 6.0f, IM_COL32(255, 255, 255, 50), 48, 1.2f);
@@ -2897,10 +2934,9 @@ void editor_mode::add_chunks_around(int const Count)
void editor_mode::handle_terrain_click(bool const Shift)
{
- glm::dvec3 const offset = GfxRenderer->Mouse_Position();
- if (glm::length(offset) < 1e-3)
- return; // nothing under the cursor (yet)
- glm::dvec3 const world = Camera.Pos + offset;
+ glm::dvec3 world;
+ if (false == cursor_on_ground(world))
+ return; // nothing under the cursor
switch (m_terrain_tool)
{
case terrain_tool::chunks:
@@ -3350,7 +3386,7 @@ bool editor_mode::save()
if (auto const area{editor_orthophoto::area_lines(m_orthophoto.area())}; false == m_orthophoto_scenery.empty() && area != m_orthophoto_area_mark)
{
m_orthophoto_area_mark = area;
- scene::Layers.mark(scene::layer_handle{1}, "//$a", area);
+ scene::Layers.mark(scene::layer_handle{1}, "//$z", area);
}
auto const controls{turntable_controls(rootstatements)};
auto const noses{nose_controls(rootstatements)};
@@ -3403,6 +3439,7 @@ void editor_mode::toggle_include(scene::instance_handle const Instance)
return;
}
scene::Layers.removed(Instance, false == included.removed);
+ m_drives_standing.reset();
ui()->set_status(format(included.removed ? STR_C("Include of \"%s\" removed") : STR_C("Include of \"%s\" restored"), included.file->c_str()));
}
@@ -3439,6 +3476,7 @@ void editor_mode::restore_includes(EditorSnapshot &Snapshot)
}
scene::Layers.removed(instance, false == scene::Layers.instance(instance).removed);
}
+ m_drives_standing.reset();
for (auto &entry : Snapshot.directives)
{
auto current = scene::Layers.directive(entry.first);
@@ -3483,6 +3521,7 @@ void editor_mode::select_include(scene::instance_handle const Instance)
void editor_mode::set_include_directive(scene::instance_handle const Instance, std::string const &Directive)
{
+ m_drives_standing.reset();
std::string file;
std::vector values;
if (scene::Layers.tracked(Instance) && editor_includes::parse_directive(Directive, file, values) && scene::Layers.instance(Instance).file != nullptr &&
@@ -3515,19 +3554,51 @@ void editor_mode::apply_include()
}
}
auto before = scene::Layers.directive(m_instance);
+ if (false == m_include.info.signal_kind.empty()
+ && std::ranges::any_of(m_include.info.parameters, [](auto const &Parameter) { return Parameter.id == 6 && Parameter.role == "texture"; }))
+ {
+ // the drawn plate of a signal follows its name; a plate picked from the textures stays, and so does a drawn one given
+ // another name by hand. While the name is cleared or one the plate can't carry, the plate keeps the last name, and
+ // follows again once a usable name is typed. No plate, or the texture named like the signal the editor gave before the
+ // plates were drawn, become the drawn one. The look, the index and the m of the plate go with it
+ std::string file;
+ std::vector previous;
+ if (editor_includes::parse_directive(before, file, previous) && previous.size() >= 6 && m_include.values.size() >= 6)
+ {
+ auto const look{signal_plate_style(previous[5])};
+ auto const carried = [&](std::string const &Name) { return Name != "none" && signal_plate_drawn(signal_plate(Name, look)); };
+ if (previous[0] != m_include.values[0] && m_include.values[5] == previous[5] && carried(m_include.values[0])
+ && (previous[5] == signal_plate(previous[0], look) || (false == carried(previous[0]) && signal_plate_drawn(previous[5])) || signal_plate_blank(previous[0], previous[5])))
+ m_include.values[5] = signal_plate(m_include.values[0], look);
+ }
+ }
auto const directive = editor_includes::compose_directive(m_include.target, m_include.values);
if (directive == before)
return;
std::string read_before;
std::string read_after;
- if (false == m_include.info.signal_read.empty())
+ // a signal renamed: its indicators are named after it
+ std::string name_before;
+ glm::dvec3 standing{0.0};
+ // the signal templates known, though no signal tool looked for them yet
+ if (m_include.info.category == "signal")
+ signal_scan(true);
+ if (false == m_include.info.signal_read.empty() || signal_template_of(m_include.target) != nullptr)
{
std::string file;
std::vector previous;
if (editor_includes::parse_directive(before, file, previous))
{
- read_before = editor_includes::substitute(m_include.info.signal_read, previous);
- read_after = editor_includes::substitute(m_include.info.signal_read, m_include.values);
+ if (false == m_include.info.signal_read.empty())
+ {
+ read_before = editor_includes::substitute(m_include.info.signal_read, previous);
+ read_after = editor_includes::substitute(m_include.info.signal_read, m_include.values);
+ }
+ if (previous.size() >= 4 && false == m_include.values.empty() && previous.front() != m_include.values.front())
+ {
+ name_before = previous.front();
+ standing = scene::Layers.instance(m_instance).context.offset + glm::dvec3{std::strtod(previous[1].c_str(), nullptr), std::strtod(previous[2].c_str(), nullptr), std::strtod(previous[3].c_str(), nullptr)};
+ }
}
}
if (false == m_include_gesture)
@@ -3546,6 +3617,12 @@ void editor_mode::apply_include()
else if (read_before != read_after && false == m_history.empty())
signal_renamed(read_before, read_after, m_history.back());
set_include_directive(m_instance, directive);
+ if (false == name_before.empty() && false == m_history.empty())
+ {
+ std::vector> carried;
+ signal_indicators_renamed(name_before, m_include.values.front(), standing, carried);
+ history_add_directives(m_history.back(), carried);
+ }
}
void editor_mode::place_include(std::string const &File, int const RotationMode, float const FixedRotation)
@@ -3625,18 +3702,11 @@ void editor_mode::export_scenery()
void editor_mode::handle_terrain_brush(double Deltatime)
{
- // world point under the cursor (Mouse_Position is camera-relative, like the brush placement uses)
- glm::dvec3 const offset = GfxRenderer->Mouse_Position();
- glm::dvec3 world = Camera.Pos + offset;
- if (m_terrain_tool == terrain_tool::holes || m_terrain_tool == terrain_tool::grass)
- {
- // the ground itself: the cursor may be over a hole (and what's seen through it), or over the blades of the grass
- if (false == terrain_cursor(world))
- return;
- }
- else if (glm::length(offset) < 1e-3)
+ // the ground itself along the ray through the cursor in this frame
+ glm::dvec3 world;
+ if (false == terrain_cursor(world))
return;
- // only when the cursor is over the terrain (avoids editing on a stale depth read)
+ // only when the cursor is over the terrain
if (terrain_at(world.x, world.z) == nullptr)
return;
@@ -3695,12 +3765,20 @@ void editor_mode::handle_terrain_brush(double Deltatime)
}
}
+bool editor_mode::cursor_on_ground(glm::dvec3 &World)
+{
+ if (m_streamer.active() && terrain_cursor(World))
+ return true;
+ // no terrain under the ray: the depth read back under the cursor, as before, where it hit anything
+ if (false == GfxRenderer->Mouse_Hit())
+ return false;
+ World = Camera.Pos + GfxRenderer->Mouse_Position();
+ return true;
+}
+
bool editor_mode::terrain_cursor(glm::dvec3 &World) const
{
- // along the ray to what the depth under the cursor shows, or, with nothing there, the ray through the cursor
- glm::dvec3 const offset = GfxRenderer->Mouse_Position();
- if (glm::length(offset) > 1e-3)
- return m_streamer.raycast(Camera.Pos, glm::normalize(offset), 5000.0, World);
+ // along the ray through the cursor as it is in this frame: the depth read back lags a frame behind
ImGuiIO const &io = ImGui::GetIO();
if (io.DisplaySize.x <= 0.0f || io.DisplaySize.y <= 0.0f)
return false;
@@ -3714,7 +3792,11 @@ bool editor_mode::terrain_cursor(glm::dvec3 &World) const
auto const direction = point(0.5f) - point(0.0f);
if (glm::length(direction) < 1e-9)
return false;
- return m_streamer.raycast(GfxRenderer->Camera_Position() + point(0.0f), glm::normalize(direction), 5000.0, World);
+ // the top view sees from 10 km behind the plane of the camera (the near plane of its projection): the ray starts there,
+ // so the ground higher than the camera is met too
+ auto const back{Global.EditorOrtho ? 10000.0 : 0.0};
+ auto const along{glm::normalize(direction)};
+ return m_streamer.raycast(GfxRenderer->Camera_Position() + point(0.0f) - along * back, along, 5000.0 + back, World);
}
void editor_mode::render_grass_ui()
@@ -3871,10 +3953,10 @@ void editor_mode::convert_selected_chunks()
bool editor_mode::pick_terrain_target()
{
- glm::dvec3 const offset = GfxRenderer->Mouse_Position();
- if (glm::length(offset) < 1e-3)
+ glm::dvec3 world;
+ if (false == cursor_on_ground(world))
return false; // nothing under the cursor
- m_terrain_target = static_cast(Camera.Pos.y + offset.y);
+ m_terrain_target = static_cast(world.y);
m_terrain_status = format(STR_C("Target height: %.2f m"), m_terrain_target);
return true;
}
@@ -3939,6 +4021,11 @@ void editor_mode::capture_terrain()
// other surface, so the point can hang over the ground by as much as the orthophoto is lifted, or lie on the flat sheet
// the orthophoto makes where it's not fitted to the ground. what's put in the scenery is to stand on the ground itself
glm::dvec3 editor_mode::placement_on_ground(glm::dvec3 Location)
+{
+ return ground_at(Location);
+}
+
+glm::dvec3 editor_mode::ground_at(glm::dvec3 Location) const
{
double constexpr reach = 2.0; // the ground is asked about this far around the point
double constexpr slack = 0.5; // a surface this far over the point still is what the cursor landed on
@@ -4095,6 +4182,9 @@ void editor_mode::render_map_menu()
{
if (false == ImGui::BeginMenu(STR_C("Map")))
return;
+ if (ImGui::MenuItem(STR_C("Minimap"), "Ctrl+M", m_minimap.is_open()))
+ m_minimap.toggle();
+ ImGui::Separator();
bool enabled = m_orthophoto.enabled();
if (ImGui::MenuItem(STR_C("Orthophoto"), nullptr, enabled))
choose_orthophoto(false == enabled);
@@ -4408,6 +4498,14 @@ void editor_mode::render_view_menu()
ImGui::MenuItem(STR_C("Show lanes"), nullptr, &m_roadtool.lanes);
if (ImGui::IsItemHovered())
ImGui::SetTooltip("%s", STR_C("The lanes of the roads drawn as the paths the vehicles take"));
+ if (ImGui::MenuItem(STR_C("Cursor drawn into the picture (streams)"), nullptr, m_draw_cursor))
+ {
+ m_draw_cursor = !m_draw_cursor;
+ ui_layer::draw_cursor(m_draw_cursor);
+ }
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("%s", STR_C("The pointer drawn by the editor into the frame instead of the one of the system: seen by those watching a stream\n"
+ "or a recording of the window (Discord, OBS, the capture of the system), which leave the system pointer out"));
if (ImGui::MenuItem(STR_C("Structure gauge"), nullptr, m_gauge.is_open()))
m_gauge.toggle();
if (ImGui::IsItemHovered())
@@ -4652,6 +4750,26 @@ void editor_mode::terrain_workspace(bool const Open)
m_terrain_spacing = m_streamer.manifest().spacing;
}
+editor_mode::texture_offer editor_mode::terrain_texture_offer(char const *None)
+{
+ return {STR_C("In the palette and on the water of this terrain:"),
+ [this]() {
+ std::vector list;
+ auto const add = [&](std::string const &Name, char const *Note) {
+ if (Name.empty() || Name == "none" || std::any_of(list.begin(), list.end(), [&](texture_use const &Use) { return Use.name == Name; }))
+ return;
+ list.push_back({null_handle, Name, 0, Note});
+ };
+ for (auto const &layer : m_streamer.manifest().layers)
+ add(layer.material, STR_C("In the palette of the terrain"));
+ add(m_streamer.manifest().water_material, STR_C("The default water material"));
+ for (auto const &body : m_streamer.water())
+ add(body.material, STR_C("On a body of water"));
+ return list;
+ },
+ None, ""};
+}
+
void editor_mode::render_terrain_tool_options()
{
// the orthophoto has its settings among the base layers in the layers window, see render_base_layers()
@@ -4674,14 +4792,13 @@ void editor_mode::render_object_menu()
void editor_mode::add_area_fill_point()
{
- // like the other placement tools, the point comes from the depth buffer under the cursor
- // (ground geometry only), relative to the camera
- glm::dvec3 const offset = GfxRenderer->Mouse_Position();
- if (glm::length(offset) < 1e-3)
- return; // no ground under the cursor (yet)
+ // the ground along the ray through the cursor in this frame
+ glm::dvec3 world;
+ if (false == cursor_on_ground(world))
+ return; // no ground under the cursor
// the outline gives the fill the height to look for the ground at, and the height of what it finds no ground for
- m_fill_points.push_back(placement_on_ground(Camera.Pos + offset));
+ m_fill_points.push_back(placement_on_ground(world));
}
void editor_mode::undo_last_area_fill()
@@ -4911,7 +5028,8 @@ void editor_mode::render_area_fill()
{
ImGui::TextDisabled(STR_C("LMB: add outline point Backspace: remove last point"));
double const area = polygon_area_xz(m_fill_points);
- ImGui::Text(STR_C("Points: %zu Area: %.0f m² (%.2f ha)"), m_fill_points.size(), area, area / 10000.0);
+ // the square sign written as its utf-8 bytes: the game is built without /utf-8 where it has the debug symbols
+ ImGui::Text(STR_C("Points: %zu Area: %.0f m\xC2\xB2 (%.2f ha)"), m_fill_points.size(), area, area / 10000.0);
if (ImGui::Button(STR_C("Remove last point")) && !m_fill_points.empty())
m_fill_points.pop_back();
ImGui::SameLine();
@@ -5379,7 +5497,7 @@ void editor_mode::render_workspaces()
};
area const areas[] = {
{STR_C("Surroundings"), work_area::surroundings, editor_icons::icon::work_surroundings, STR_C("Models around the line: select, insert, brush, area fill, copy to the node bank")},
- {STR_C("Tracks"), work_area::tracks, editor_icons::icon::work_tracks, STR_C("Tracks and switches, signals, objects along the track, checks of the line")},
+ {STR_C("Tracks"), work_area::tracks, editor_icons::icon::work_tracks, STR_C("Tracks and switches, signals, kilometrage and posts along the track, checks of the line")},
{STR_C("Roads"), work_area::roads, editor_icons::icon::work_roads, STR_C("Roads and junctions, level crossings, the points where the traffic comes and goes")},
{STR_C("Terrain"), work_area::terrain, editor_icons::icon::work_terrain, STR_C("Heightmap terrain: chunks, sculpting, painting, water, orthophoto")},
{STR_C("Catenary"), work_area::catenary, editor_icons::icon::work_catenary, STR_C("The overhead catenary: poles with cantilevers, gantries, the wires of the chains")},
@@ -5498,7 +5616,7 @@ void editor_mode::render_help_menu()
ImGui::SetTooltip("%s", STR_C("The keys of the editor, for each field of work"));
ImGui::MenuItem(STR_C("Tutorial"), nullptr, &m_first_steps_open);
if (ImGui::IsItemHovered())
- ImGui::SetTooltip("%s", STR_C("Thirteen short lessons with clips and drawings: the camera, laying track, curves, correcting a curve, joining, switches, signals and posts, fixing, the gizmo, the grade line, terrain, older sceneries, saving and driving"));
+ ImGui::SetTooltip("%s", STR_C("Short lessons: the camera, laying track, curves, the radius at the bends, correcting a curve, joining, switches, switch templates, signals and posts, a whole line step by step, fixing, the gizmo, the grade line, terrain, older sceneries, saving and driving"));
ImGui::EndMenu();
}
@@ -5507,6 +5625,12 @@ void editor_mode::first_step_done(first_step const Step)
m_first_steps_done[static_cast(Step)] = true;
}
+void editor_mode::open_kilometrage()
+{
+ choose_work_area(work_area::tracks);
+ show_track_tab(track_tab::kilometrage);
+}
+
namespace
{
@@ -5573,23 +5697,92 @@ void tutorial_profile_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const Hi
List.Flags = flags;
List.AddPolyline(ground.data(), static_cast(ground.size()), IM_COL32(170, 130, 80, 220), 0, 1.5f);
auto const lift{static_cast(0.5 + 0.5 * std::sin(Time * 1.6))};
- ImVec2 const points[]{ImVec2(x_of(0.0f), y_of(0.32f)), ImVec2(x_of(0.38f), y_of(0.42f)), ImVec2(x_of(0.66f), y_of(0.35f + 0.4f * lift)), ImVec2(x_of(1.0f), y_of(0.55f))};
- List.AddPolyline(points, 4, IM_COL32(170, 170, 170, 160), 0, 1.0f);
- List.AddPolyline(points, 4, IM_COL32(90, 220, 110, 255), 0, 2.5f);
- for (int i = 0; i < 4; ++i)
+ std::array const points{ImVec2(x_of(0.0f), y_of(0.32f)), ImVec2(x_of(0.38f), y_of(0.42f)), ImVec2(x_of(0.66f), y_of(0.35f + 0.4f * lift)), ImVec2(x_of(1.0f), y_of(0.55f))};
+ List.AddPolyline(points.data(), static_cast(points.size()), IM_COL32(170, 170, 170, 160), 0, 1.0f);
+ List.AddPolyline(points.data(), static_cast(points.size()), IM_COL32(90, 220, 110, 255), 0, 2.5f);
+ for (std::size_t i = 0; i < points.size(); ++i)
List.AddCircleFilled(points[i], i == 2 ? 6.0f : 4.5f, i == 2 ? kGestureLit : IM_COL32(250, 210, 80, 255));
List.AddCircle(points[2], 9.0f, kGestureLit, 0, 1.5f);
- for (int i = 0; i < 3; ++i)
+ for (std::size_t i = 0; i + 1 < points.size(); ++i)
{
auto const grade{-(points[i + 1].y - points[i].y) / (points[i + 1].x - points[i].x) * 40.0f};
- char text[32];
- std::snprintf(text, sizeof(text), "%+.1f", std::abs(grade) < 0.05f ? 0.0f : grade);
+ auto const text{std::format("{:+.1f}", std::abs(grade) < 0.05f ? 0.0f : grade)};
ImVec2 const middle{(points[i].x + points[i + 1].x) * 0.5f, (points[i].y + points[i + 1].y) * 0.5f - ImGui::GetTextLineHeight() - 2.0f};
- List.AddText(ImVec2(middle.x - ImGui::CalcTextSize(text).x * 0.5f, middle.y), i == 0 ? IM_COL32(200, 200, 200, 255) : IM_COL32(255, 255, 255, 255), text);
+ List.AddText(ImVec2(middle.x - ImGui::CalcTextSize(text.c_str()).x * 0.5f, middle.y), i == 0 ? IM_COL32(200, 200, 200, 255) : IM_COL32(255, 255, 255, 255), text.c_str());
}
gesture_mouse(List, ImVec2(points[2].x + 12.0f, points[2].y + 10.0f), height * 0.18f, "LMB");
}
+// the points of a switch clicked one after another: its start, the ends of its two tracks, the way on, the points along the diverging track
+void tutorial_template_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time)
+{
+ auto const width{High.x - Low.x};
+ auto const height{High.y - Low.y};
+ auto const at = [&](float const X, float const Y) { return ImVec2(Low.x + width * X, Low.y + height * Y); };
+ auto const curve = [&](float const Share) { return at(0.08f + 0.70f * Share, 0.72f - 0.42f * Share * Share); };
+ auto const shown{static_cast(std::fmod(static_cast(Time), 10.0f))};
+ std::vector line;
+ for (int i = 0; i <= 24; ++i)
+ line.push_back(curve(static_cast(i) / 24.0f));
+ List.AddLine(at(0.08f, 0.72f), at(0.78f, 0.72f), IM_COL32(150, 150, 150, 130), 3.0f);
+ List.AddPolyline(line.data(), static_cast(line.size()), IM_COL32(150, 150, 150, 130), ImDrawFlags_None, 3.0f);
+ std::array const points{at(0.08f, 0.72f), at(0.78f, 0.72f), curve(1.0f), at(0.94f, 0.14f), curve(0.28f), curve(0.5f), curve(0.72f), curve(0.88f)};
+ if (shown >= 1)
+ List.AddLine(points[0], points[1], IM_COL32(255, 255, 255, 230), 1.5f);
+ if (shown >= 3)
+ List.AddLine(points[2], points[3], IM_COL32(90, 200, 255, 230), 1.5f);
+ for (int i = 0; i < static_cast(points.size()) && i <= shown; ++i)
+ {
+ List.AddCircleFilled(points[i], 4.0f, i < 4 ? IM_COL32(255, 225, 60, 255) : IM_COL32(120, 255, 120, 255));
+ if (i < 4)
+ List.AddText(ImVec2(points[i].x + 6.0f, points[i].y - 18.0f), IM_COL32(255, 255, 255, 255), std::to_string(i + 1).c_str());
+ }
+ if (shown >= 8)
+ List.AddPolyline(line.data(), static_cast(line.size()), IM_COL32(255, 90, 200, 255), ImDrawFlags_None, 2.0f);
+}
+
+// the radius of the curve at a bend: the two straights clicked stay, the curve between them grows from sharp to gentle and back
+void tutorial_corner_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time)
+{
+ auto const width{High.x - Low.x};
+ auto const height{High.y - Low.y};
+ glm::vec2 const from{Low.x + width * 0.04f, Low.y + height * 0.80f};
+ glm::vec2 const vertex{Low.x + width * 0.50f, Low.y + height * 0.18f};
+ glm::vec2 const to{Low.x + width * 0.96f, Low.y + height * 0.80f};
+ auto const point = [](glm::vec2 const Point) { return ImVec2(Point.x, Point.y); };
+ List.AddLine(point(from), point(vertex), IM_COL32(150, 150, 150, 130), 1.0f);
+ List.AddLine(point(vertex), point(to), IM_COL32(150, 150, 150, 130), 1.0f);
+ List.AddCircleFilled(point(vertex), 4.0f, IM_COL32(255, 255, 255, 255));
+ // there and back in 8 s, a moment at each end
+ auto const cycle{std::fmod(static_cast(Time), 8.0f) / 8.0f};
+ auto const swing{std::clamp(1.3f - std::abs(cycle * 2.0f - 1.0f) * 1.6f, 0.0f, 1.0f)};
+ auto const share{swing * swing * (3.0f - 2.0f * swing)};
+ auto const in{glm::normalize(from - vertex)};
+ auto const out{glm::normalize(to - vertex)};
+ auto const tangent{glm::mix(0.12f, 0.92f, share) * glm::length(from - vertex)};
+ auto const half{std::acos(glm::dot(in, out)) * 0.5f};
+ auto const centre{vertex + glm::normalize(in + out) * (tangent / std::cos(half))};
+ auto const start{vertex + in * tangent};
+ auto const end{vertex + out * tangent};
+ auto const begin{std::atan2(start.y - centre.y, start.x - centre.x)};
+ auto sweep{std::atan2(end.y - centre.y, end.x - centre.x) - begin};
+ while (sweep > glm::pi())
+ sweep -= glm::two_pi();
+ while (sweep < -glm::pi())
+ sweep += glm::two_pi();
+ auto const radius{glm::length(start - centre)};
+ std::vector line{point(from)};
+ for (int i = 0; i <= 32; ++i)
+ {
+ auto const angle{begin + sweep * static_cast(i) / 32.0f};
+ line.push_back(ImVec2(centre.x + radius * std::cos(angle), centre.y + radius * std::sin(angle)));
+ }
+ line.push_back(point(to));
+ List.AddPolyline(line.data(), static_cast(line.size()), IM_COL32(230, 190, 90, 255), ImDrawFlags_None, 3.0f);
+ auto const label{format(STR_C("R %.0f m: %s"), glm::mix(300.0, 6000.0, static_cast(share)), share < 0.5f ? STR_C("a sharp curve, a slow train") : STR_C("a gentle curve, a fast train"))};
+ List.AddText(ImVec2(Low.x + (width - ImGui::CalcTextSize(label.c_str()).x) * 0.5f, High.y - ImGui::GetTextLineHeight() - 4.0f), IM_COL32(235, 235, 235, 255), label.c_str());
+}
+
// the route of the grade line picked on the map: a click lights up the whole line through the track, Shift and a box only the
// tracks between the outermost ones in it; beside it the strip with a point of the line dragged
void tutorial_route_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time)
@@ -5603,7 +5796,7 @@ void tutorial_route_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High
auto const mix = [](ImVec2 const A, ImVec2 const B, float const T) { return ImVec2(A.x + (B.x - A.x) * T, A.y + (B.y - A.y) * T); };
auto const ease = [](float const T) { auto const t{std::clamp(T, 0.0f, 1.0f)}; return t * t * (3.0f - 2.0f * t); };
// the joints of the tracks of the line, and a siding going off it at a switch
- ImVec2 const joints[]{at(0.04f, 0.72f), at(0.18f, 0.64f), at(0.32f, 0.54f), at(0.46f, 0.48f), at(0.60f, 0.46f), at(0.74f, 0.42f), at(0.88f, 0.32f), at(0.98f, 0.24f)};
+ std::array const joints{at(0.04f, 0.72f), at(0.18f, 0.64f), at(0.32f, 0.54f), at(0.46f, 0.48f), at(0.60f, 0.46f), at(0.74f, 0.42f), at(0.88f, 0.32f), at(0.98f, 0.24f)};
int constexpr tracks{7};
List.AddBezierQuadratic(joints[3], at(0.58f, 0.52f), at(0.80f, 0.66f), IM_COL32(130, 130, 130, 200), 2.0f);
auto const cycle{static_cast(std::fmod(Time, 8.0))};
@@ -5642,7 +5835,7 @@ void tutorial_route_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High
for (auto const &joint : joints)
List.AddCircleFilled(joint, 2.5f, IM_COL32(220, 220, 220, 255));
gesture_mouse(List, ImVec2(cursor.x + 2.0f, cursor.y + 2.0f), std::round(height * 0.16f), "LMB");
- auto const caption{boxing ? STR_C("Shift + a box: between the outermost") : STR_C("LMB on a track: its whole line")};
+ auto const caption{boxing ? STR_C("Shift + a box: between the outermost tracks") : STR_C("LMB on a track: its whole line")};
List.AddText(ImVec2(Low.x + 6.0f, High.y - ImGui::GetTextLineHeight() - 4.0f), IM_COL32(230, 230, 230, 230), caption);
}
@@ -5658,13 +5851,10 @@ void tutorial_signal_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const Hig
// the track seen from above: sleepers and the two rails
auto const middle{at(0.0f, 0.5f).y};
auto const gauge{height * 0.07f};
+ for (int sleeper = 0; sleeper < 40; ++sleeper)
{
- float x{0.02f};
- while (x < 1.0f)
- {
- List.AddLine(ImVec2(at(x, 0.0f).x, middle - gauge * 1.6f), ImVec2(at(x, 0.0f).x, middle + gauge * 1.6f), IM_COL32(110, 90, 70, 255), 3.0f);
- x += 0.025f;
- }
+ auto const x{at(0.02f + 0.025f * static_cast(sleeper), 0.0f).x};
+ List.AddLine(ImVec2(x, middle - gauge * 1.6f), ImVec2(x, middle + gauge * 1.6f), IM_COL32(110, 90, 70, 255), 3.0f);
}
List.AddLine(ImVec2(Low.x, middle - gauge), ImVec2(High.x, middle - gauge), IM_COL32(200, 200, 205, 255), 2.0f);
List.AddLine(ImVec2(Low.x, middle + gauge), ImVec2(High.x, middle + gauge), IM_COL32(200, 200, 205, 255), 2.0f);
@@ -5691,11 +5881,9 @@ void tutorial_signal_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const Hig
ImVec2 const head_high{foot.x + height * 0.04f, foot.y - height * 0.06f};
List.AddRectFilled(head_low, head_high, IM_COL32(25, 25, 25, 255), height * 0.03f);
List.AddRect(head_low, head_high, IM_COL32(150, 150, 150, 255), height * 0.03f);
- for (int i = 0; i < 3; ++i)
- {
- ImU32 const lights[]{IM_COL32(230, 60, 50, 255), IM_COL32(70, 210, 90, 255), IM_COL32(240, 240, 240, 255)};
- List.AddCircleFilled(ImVec2(foot.x, head_low.y + height * (0.04f + 0.065f * i)), height * 0.025f, lights[i]);
- }
+ std::array const lights{IM_COL32(230, 60, 50, 255), IM_COL32(70, 210, 90, 255), IM_COL32(240, 240, 240, 255)};
+ for (std::size_t i = 0; i < lights.size(); ++i)
+ List.AddCircleFilled(ImVec2(foot.x, head_low.y + height * (0.04f + 0.065f * static_cast(i))), height * 0.025f, lights[i]);
List.AddText(ImVec2(foot.x - height * 0.06f - ImGui::CalcTextSize("S1").x, foot.y - line), IM_COL32(255, 255, 255, 230), "S1");
}
gesture_mouse(List, ImVec2(cursor.x + 2.0f, cursor.y + 2.0f), std::round(height * 0.16f), "LMB");
@@ -5706,15 +5894,14 @@ void tutorial_signal_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const Hig
auto const shown{static_cast((cycle - 4.3f) / 0.35f) + 1};
for (int i = 0; i < std::min(shown, 9); ++i)
{
- auto const x{at(0.07f + 0.105f * i, 0.0f).x};
+ auto const x{at(0.07f + 0.105f * static_cast(i), 0.0f).x};
auto const foot{middle - gauge * 3.2f};
List.AddRectFilled(ImVec2(x - 3.0f, foot - height * 0.14f), ImVec2(x + 3.0f, foot), IM_COL32(240, 240, 240, 255), 1.0f);
- char text[16];
- std::snprintf(text, sizeof(text), "12.%d", i + 1);
- auto const size{ImGui::CalcTextSize(text)};
- List.AddText(ImVec2(std::round(x - size.x * 0.5f), foot - height * 0.14f - size.y - 1.0f), IM_COL32(255, 220, 120, 255), text);
+ auto const text{std::format("12.{}", i + 1)};
+ auto const size{ImGui::CalcTextSize(text.c_str())};
+ List.AddText(ImVec2(std::round(x - size.x * 0.5f), foot - height * 0.14f - size.y - 1.0f), IM_COL32(255, 220, 120, 255), text.c_str());
}
- List.AddText(ImVec2(Low.x + 6.0f, High.y - line - 4.0f), IM_COL32(230, 230, 230, 230), STR_C("B: the hectometre posts of the whole line at once"));
+ List.AddText(ImVec2(Low.x + 6.0f, High.y - line - 4.0f), IM_COL32(230, 230, 230, 230), STR_C("B: posts every 100 m along the whole line at once"));
}
// a vehicle seen from the side, drawn simply: the body with its windows on two bogies
@@ -5728,9 +5915,12 @@ void tutorial_vehicle(ImDrawList &List, ImVec2 const Low, ImVec2 const High, ImU
auto const windows{Locomotive ? 2 : 5};
for (int i = 0; i < windows; ++i)
{
- auto const left{Locomotive ? (i == 0 ? Low.x + width * 0.06f : High.x - width * 0.2f) : Low.x + width * (0.08f + 0.18f * i)};
+ // a locomotive has a window at each end, a coach a row of them
+ auto window_x{Low.x + width * (0.08f + 0.18f * static_cast(i))};
+ if (Locomotive)
+ window_x = (i == 0 ? Low.x + width * 0.06f : High.x - width * 0.2f);
auto const size{Locomotive ? width * 0.14f : width * 0.12f};
- List.AddRectFilled(ImVec2(left, Low.y + height * 0.15f), ImVec2(left + size, Low.y + height * 0.42f), IM_COL32(30, 40, 50, 255), 2.0f);
+ List.AddRectFilled(ImVec2(window_x, Low.y + height * 0.15f), ImVec2(window_x + size, Low.y + height * 0.42f), IM_COL32(30, 40, 50, 255), 2.0f);
}
for (float const share : {0.22f, 0.78f})
{
@@ -5748,14 +5938,15 @@ void tutorial_trainset_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const H
auto const height{High.y - Low.y};
auto const at = [&](float const X, float const Y) { return ImVec2(Low.x + width * X, Low.y + height * Y); };
auto const cycle{static_cast(std::fmod(Time, 9.0))};
- ImU32 const colours[]{IM_COL32(200, 60, 50, 255), IM_COL32(60, 120, 70, 255), IM_COL32(70, 100, 160, 255)};
+ std::array const colours{IM_COL32(200, 60, 50, 255), IM_COL32(60, 120, 70, 255), IM_COL32(70, 100, 160, 255)};
auto const line{ImGui::GetTextLineHeight()};
// the list: the side view of each vehicle and its name
- for (int i = 0; i < 3; ++i)
+ for (std::size_t i = 0; i < colours.size(); ++i)
{
- auto const top{0.08f + 0.28f * i};
- auto const clicked{cycle > 0.8f + 1.4f * i && cycle < 1.2f + 1.4f * i};
- if (clicked)
+ auto const slot{static_cast(i)};
+ auto const top{0.08f + 0.28f * slot};
+ // lit while it's double clicked
+ if (cycle > 0.8f + 1.4f * slot && cycle < 1.2f + 1.4f * slot)
List.AddRectFilled(at(0.02f, top - 0.02f), at(0.40f, top + 0.24f), IM_COL32(90, 175, 255, 70), 3.0f);
tutorial_vehicle(List, at(0.03f, top), at(0.16f, top + 0.2f), colours[i], i == 0);
List.AddRectFilled(at(0.19f, top + 0.03f), at(0.36f, top + 0.03f + line / height * 0.6f), IM_COL32(220, 220, 220, 200), 2.0f);
@@ -5763,7 +5954,7 @@ void tutorial_trainset_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const H
}
// the cursor goes down the list double clicking, then to the button
auto const row{std::min(2, static_cast(std::max(0.0f, cycle - 0.4f) / 1.4f))};
- ImVec2 cursor{at(0.30f, 0.16f + 0.28f * row)};
+ ImVec2 cursor{at(0.30f, 0.16f + 0.28f * static_cast(row))};
auto const added{std::clamp(static_cast((cycle - 0.8f) / 1.4f) + 1, 0, 3)};
auto const button_low{at(0.55f, 0.08f)};
auto const button_high{at(0.95f, 0.30f)};
@@ -5780,10 +5971,10 @@ void tutorial_trainset_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const H
auto const run{cycle > 5.6f ? (cycle - 5.6f) * (cycle - 5.6f) * width * 0.06f : 0.0f};
auto const car{width * 0.15f};
List.PushClipRect(ImVec2(at(0.44f, 0.0f).x, Low.y), High, true);
- for (int i = 0; i < added; ++i)
+ for (std::size_t i = 0; i < static_cast(added); ++i)
{
- auto const left{at(0.46f, 0.0f).x + (car + 3.0f) * i - run};
- tutorial_vehicle(List, ImVec2(left, rail - height * 0.24f), ImVec2(left + car, rail), colours[i], i == 0);
+ auto const front{at(0.46f, 0.0f).x + (car + 3.0f) * static_cast(i) - run};
+ tutorial_vehicle(List, ImVec2(front, rail - height * 0.24f), ImVec2(front + car, rail), colours[i], i == 0);
}
List.PopClipRect();
gesture_mouse(List, ImVec2(cursor.x + 2.0f, cursor.y + 2.0f), std::round(height * 0.16f), "LMB");
@@ -5804,7 +5995,8 @@ void tutorial_terrain_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const Hi
auto const x_of = [&](float const Share) { return Low.x + width * Share; };
auto const y_of = [&](float const Level) { return Low.y + height * (0.95f - 0.75f * Level); };
int constexpr steps{80};
- std::vector ground, track;
+ std::vector ground;
+ std::vector track;
for (int i = 0; i <= steps; ++i)
{
auto const share{static_cast(i) / steps};
@@ -5815,15 +6007,14 @@ void tutorial_terrain_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const Hi
List.Flags &= ~ImDrawListFlags_AntiAliasedFill;
for (int i = 0; i < steps; ++i)
{
- ImVec2 const quad[]{ground[i], ground[i + 1], ImVec2(ground[i + 1].x, High.y), ImVec2(ground[i].x, High.y)};
- List.AddConvexPolyFilled(quad, 4, IM_COL32(95, 120, 70, 120));
+ std::array const quad{ground[i], ground[i + 1], ImVec2(ground[i + 1].x, High.y), ImVec2(ground[i].x, High.y)};
+ List.AddConvexPolyFilled(quad.data(), static_cast(quad.size()), IM_COL32(95, 120, 70, 120));
}
if (eased > 0.99f)
for (int i = 0; i < steps; ++i)
{
auto const fill{track[i].y < ground[i].y};
- ImVec2 const quad[]{track[i], track[i + 1], ground[i + 1], ground[i]};
- List.AddQuadFilled(quad[0], quad[1], quad[2], quad[3], fill ? IM_COL32(190, 150, 90, 150) : IM_COL32(60, 45, 30, 150));
+ List.AddQuadFilled(track[i], track[i + 1], ground[i + 1], ground[i], fill ? IM_COL32(190, 150, 90, 150) : IM_COL32(60, 45, 30, 150));
}
List.Flags = flags;
List.AddPolyline(ground.data(), static_cast(ground.size()), IM_COL32(150, 190, 110, 255), 0, 1.5f);
@@ -5834,14 +6025,215 @@ void tutorial_terrain_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const Hi
} // namespace
-void editor_mode::render_first_steps()
+// a lesson of the tutorial: its clip or sketch, the mouse and the keys it teaches, the steps to try and the button under it
+struct editor_mode::tutorial_lesson
{
- if (false == m_first_steps_open)
+ // what the button under a lesson does: opens the tool the lesson is about, or switches the view
+ enum class trial { reading, top, lay, turnout, select, profile, terrain, plan, trainset, signals, station };
+ struct input
{
- if (false == m_tutorial_clip.path().empty())
- m_tutorial_clip.close();
- return;
- }
+ char const *keys;
+ char const *text;
+ };
+ struct goal
+ {
+ first_step step;
+ char const *text;
+ };
+ char const *title;
+ char const *clip;
+ std::vector inputs;
+ std::vector goals;
+ trial action;
+ void (*sketch)(ImDrawList &, ImVec2, ImVec2, double){nullptr};
+};
+
+std::vector const &editor_mode::tutorial_lessons()
+{
+ using trial = tutorial_lesson::trial;
+ static std::vector const lessons{
+ {"Looking around",
+ "camera",
+ {{"RMB + move", "Hold the right mouse button and move the mouse to look around"},
+ {"RMB + W S A D", "Keep holding the right button and press W S A D to fly around; E takes you up, Q down"},
+ {"O", "Switches between the view from above, like a map, and the normal 3D view"},
+ {"wheel", "Zooms in and out at the mouse pointer"},
+ {"MMB + move", "Press the wheel down and drag to move the view, from above and in 3D"},
+ {"Y", "Rides the camera along the track under the mouse pointer, as from a train; Y again gets off. The tools keep working on the way"},
+ {"RMB + W S A D", "While riding: W and S drive, Shift faster; A and D jump to the next track on the left or right; Z picks the way at the next switch"},
+ {"F", "Flies to what you have selected"}},
+ {{first_step::look, "Look around with the right mouse button held"}, {first_step::top, "Press O: from above to 3D, or back"}, {first_step::ride, "Ride along a track with Y"}},
+ trial::top},
+ {"Laying track",
+ "lay",
+ {{"F3", "Opens Tracks, the part of the editor where track is laid"},
+ {"L", "Turns laying on"},
+ {"LMB", "Click the ground where the track should start, or the end of a track to carry it on"},
+ {"LMB", "Click again wherever the track should turn; the curves are made for you. Until you press Enter it is only a line, not a track"},
+ {"Enter", "Lays the track along the line. To carry on, click its end"},
+ {"Backspace", "Removes the last point you clicked"},
+ {"Esc", "Throws away the points not laid yet, but only when pressed twice within 3 seconds: the first press just warns. With no points left, Esc stops laying"}},
+ {{first_step::tracks, "Open Tracks (F3)"}, {first_step::lay, "Turn laying on (L)"}, {first_step::laid, "Click a few points and press Enter"}},
+ trial::lay},
+ {"Curves",
+ "curves",
+ {{"LMB", "Every place where the line turns gets a curve, as big as fits. An orange label means the curve breaks the rules for the speed set in the panel"},
+ {"Tab", "To copy a curve from the aerial photo: press Tab, then click points along the middle of the curve; it ends at the last one"},
+ {"Alt", "Hold it while clicking: the direction jumps in steps of 15 degrees, or to the angle of a switch to a straight track nearby"},
+ {"0 1 2 3", "After the first point: type a number and press Enter, and the next straight piece is that many metres long"},
+ {"wheel", "The wheel alone zooms, as everywhere"}},
+ {{first_step::bend, "Lay a track that turns"}, {first_step::trace, "Press Tab to copy a curve from the photo"}},
+ trial::lay},
+ {"Radius of the curves at the bends",
+ nullptr,
+ {{"LMB", "Where the line turns, two straight pieces meet at a corner no train could take, so the editor rounds it off with a curve"},
+ {"R", "The radius tells how big the curve is, in metres: the bigger it is, the gentler the curve and the faster a train can go round it"},
+ {"R", "The editor picks the biggest curve that fits between your points. A slight turn gets only a gentle easing in and out; a sharper one gets a real curve, eased in and out, with the outer rail raised, as the railway rules say"},
+ {"LMB", "Points too close together leave little room, so the curve comes out smaller. When it no longer meets the rules, its label turns orange: click the points further apart"},
+ {"R L h", "The label of a curve: R is the radius, L the length of the easing into it, h how much higher the outer rail is, in millimetres. A slight turn with no real curve reads 2xL"}},
+ {{first_step::bend, "Lay a track that turns and read the label of its curve"}},
+ trial::lay,
+ tutorial_corner_sketch},
+ {"Correcting a curve",
+ "plan",
+ {{"G", "Turns Plan on. Click a curve to see how it is built; its corner point and its size can be dragged in the view"},
+ {"LMB + move", "The strip in the panel shows how much the track turns along the way. Drag a flat part of it up or down to change how sharp that curve is"},
+ {"LMB + move", "Drag a sloping part sideways: the easing into the curve gets longer or shorter"},
+ {"wheel", "Over the strip, the wheel changes it in small steps"},
+ {"LMB", "Apply to the scenery: the tracks are laid again as the plan shows"}},
+ {{first_step::plan, "Open the plan of a curve"}, {first_step::plan_band, "Change the curve on the strip"}, {first_step::plan_apply, "Apply the change"}},
+ trial::plan},
+ {"Joining tracks",
+ "join",
+ {{"LMB + move", "Press on the loose end of a track (a pink ring while laying) and drag: a new track comes out of it"},
+ {"LMB", "Let go on another loose end: a curve joins the two tracks"},
+ {"LMB", "While laying, a click on a loose end joins your track to it exactly, with no gap"},
+ {"Ctrl + wheel", "Over the other end: makes the joining curve bigger or smaller"},
+ {"Shift + wheel", "Over the other end: tries another way of joining"}},
+ {{first_step::join, "Join two loose ends"}, {first_step::wheel, "Change the size of the joining curve with Ctrl+wheel"}},
+ trial::lay},
+ {"Switches",
+ "switch",
+ {{"T", "Turns Switch on. The tiles at the top choose what you put in: a switch, a slip switch or a crossing"},
+ {"LMB", "Click the track the switch should go into"},
+ {"LMB + move", "Press on it and drag: along the track sets which way the switch points, sideways which side it branches off to; let go to lay it"},
+ {"LMB + move", "Drag from a straight track onto the track beside it: two switches joining them (a crossover). Over a crossover going the other way you get a double or a scissors one"},
+ {"LMB + move", "Drag from a straight across several tracks running alongside and let go on the farthest: a row of switches leading onto each of them (a switch ladder)"},
+ {"Esc", "Back to selecting"}},
+ {{first_step::turnout, "Put a switch into a track"}},
+ trial::turnout},
+ {"Switch templates",
+ nullptr,
+ {{"T", "In Switch, the Template editor... button: ready switch shapes and your own. Point at a number to see on the drawing what it means"},
+ {"LMB", "To copy a switch from the aerial photo: Click off the view..., then click where the switch starts, the end of its straight track, the end of its branching track and one point further along that branch"},
+ {"LMB", "Then at least 3 points along the branching track: its shape and size follow them"},
+ {"Backspace", "Removes the last point; Esc stops clicking"},
+ {"O", "The view from above; the aerial photo is turned on in the Layers panel"},
+ {"LMB", "Make the template: the new switch lies on the photo where it was clicked and changes as its numbers change"}},
+ {{first_step::template_open, "Open the template editor"}, {first_step::template_clicked, "Make a template by clicking in the view"}},
+ trial::turnout,
+ tutorial_template_sketch},
+ {"Signals and posts",
+ nullptr,
+ {{"I", "Turns Signals on. Click a kind of signal in its list; it shows the signals this scenery has"},
+ {"LMB", "Click beside a track: the signal stands on that side"},
+ {"LMB + move", "Press beside the track and drag along it: the signal faces the trains going the way you dragged"},
+ {"LMB + move", "Drag a signal that already stands: it slides along its track"},
+ {"X", "Turns Kilometrage on. Click a track where you know the km, by a post or a station: the posts every 100 m and the block signals are numbered after it"},
+ {"B", "Things beside the track: posts every 100 m along a whole line at once, the W17 signs by the switches (how far a wagon may stand) and trains. The posts take their numbers from the km set with X, or from the km you type in their panel for the place you clicked"}},
+ {{first_step::signal, "Put up a signal"}, {first_step::posts, "Put up the posts along a line"}},
+ trial::signals,
+ tutorial_signal_sketch},
+ {"A whole line, step by step",
+ nullptr,
+ {{"1", "Lay the tracks of the line (L), and the switches (T) where the stations are"},
+ {"2", "Kilometrage (X): click a track where you know the km, by a post or at a station. One point is enough: the posts, the stations and the block signals count from it"},
+ {"3", "Station (under More): click a switch of the station, then give its name, its code and the number of the line"},
+ {"4", "Station signals (under More): Set the signals puts up the entry, exit and shunting signals of the whole station at once"},
+ {"5", "Line block (under More): the block signals on the line out of each station, once the stations are set"},
+ {"6", "Posts (B): click the line, then Place the posts, every 100 m along all of it"},
+ {"7", "Save with Ctrl+S, put a train on the track and drive: the last lesson"}},
+ {},
+ trial::station},
+ {"Selecting and fixing",
+ "edit",
+ {{"Esc", "Turns selecting on"},
+ {"LMB", "Click a track to select it; its ends show"},
+ {"LMB + move", "Drag an end: where tracks meet, the ones beside follow; a loose end pulls out a new track, or with Ctrl moves by itself"},
+ {"RMB", "Click a track: a menu of what can be done with it"},
+ {"Del", "Deletes what is selected"},
+ {"Ctrl + Z", "Undoes the last change; Ctrl+Y brings it back"},
+ {"Q W E", "Handles on the track to move, turn, lengthen or bend it: the next lesson"}},
+ {{first_step::select, "Select a track"}, {first_step::undo, "Undo a change"}},
+ trial::select},
+ {"Editing with the gizmo",
+ "gizmo",
+ {{"Q", "Shows arrows on the selected track: drag one to move the track"},
+ {"W", "Shows rings: drag one to turn the track, to tilt it up or down, or to raise one rail; the tracks joined to it follow"},
+ {"E", "Shows handles that make the track longer at its loose end; a curve stays as sharp as it was"},
+ {"LMB + move", "With the handles out there are also points that bend the track: drag one and the track bends after it"},
+ {"LMB", "Click a point of the track to put the handles there: Q then moves that point only, W turns the whole track around it"},
+ {"Ctrl", "Hold it while dragging to move in even steps"},
+ {"Esc", "Lets go of the point; the arrow button above the view hides the handles again"}},
+ {{first_step::gizmo, "Show the handles with Q, W or E"}, {first_step::vector, "Bend a track by one of its points, or move it with the handles"}},
+ trial::select},
+ {"The grade line",
+ nullptr,
+ {{"P", "Turns Profile on. Click a track: below the view you see how its whole line goes up and down"},
+ {"Shift + LMB", "A click adds another track; a box drawn from empty ground takes the tracks inside it. The route runs between the outermost of them, through the switches"},
+ {"LMB + move", "Drag a point of the line: the slopes on both sides of it change with it"},
+ {"LMB LMB", "Double-click the line to add a point"},
+ {"Del", "Removes the chosen point"},
+ {"LMB", "Tracks running side by side share one line: change it, press Apply to the scenery, and the tracks beside it (blue) change too"},
+ {"LMB", "To give the route open in Profile a line of its own, press Take off the common grade line"},
+ {"Ctrl + wheel", "Over the chart: stretches it up and down, so the slopes are easier to see"},
+ {"RMB + move", "Over the chart: moves along the line"}},
+ {{first_step::profile, "Open the profile of a track"}, {first_step::profile_point, "Move or add a point"}, {first_step::profile_apply, "Apply it: the tracks take the new heights"}},
+ trial::profile,
+ tutorial_route_sketch},
+ {"Terrain from the terrain model",
+ nullptr,
+ {{"L", "In a new, empty scenery the first L asks whether you want the real ground of the place or a flat plane"},
+ {"F5", "Opens Terrain; the real ground (the terrain model) is in its panel"},
+ {"LMB", "Step 1, Location: show where the scenery is, with a click on the map or by typing the place"},
+ {"LMB", "Step 2, before there are tracks: Load around the camera brings the ground of that spot from geoportal.gov.pl"},
+ {"LMB", "Step 2, once there are tracks: Tracks onto the terrain puts the tracks not fitted yet onto the real ground; Terrain under the tracks brings the ground up or down to them; The terrain of the model only loads the ground along them and leaves the tracks alone"},
+ {"F3", "The terrain to some of the tracks only: select them (F3), Terrain in the inspector"},
+ {"LMB", "A new track partly under the ground: the message above the view has Fit the ground to the track; one click builds the bank or the cutting along it"},
+ {"", "A line you shaped by hand in Profile stays as it is, even when all the tracks are fitted anew, unless you tick that the ones edited by hand go too"},
+ {"", "Tracks close side by side (under 5.1 m apart) get one common line of heights; a track crossing others where the ground is low on both sides goes under them"},
+ {"Ctrl + Z", "Takes the changes back"}},
+ {{first_step::terrain, "Open Terrain (F5)"}, {first_step::nmt, "Load the real ground"}},
+ trial::terrain,
+ tutorial_terrain_sketch},
+ {"Sceneries made before",
+ nullptr,
+ {{"LMB", "Some tracks can't be changed, for example ones put in from a ready .inc file or lying on a locked layer: the Inspector says why"},
+ {"T", "Switches laid earlier keep their shape; a template picked for one in the Inspector gives it the ready shape"},
+ {"P", "Heights saved by an older editor are read as they were saved"},
+ {"Ctrl + S", "Saving writes only what was changed; the rest of the files stays as it was"}},
+ {},
+ trial::reading},
+ {"Saving and driving",
+ nullptr,
+ {{"Ctrl + S", "Saves the scenery"},
+ {"LMB", "The trainset tool (the button below): click the track where the train should stand"},
+ {"LMB LMB", "Double-click a vehicle in the list to add it to the train; click a vehicle in the train to move it, turn it round or take it out"},
+ {"LMB", "Place and drive: the train stands on the track and you sit in the cab"}},
+ {{first_step::save, "Save the scenery"}, {first_step::drive, "Drive on the new track"}},
+ trial::trainset,
+ tutorial_trainset_sketch},
+ };
+ return lessons;
+}
+
+bool editor_mode::tutorial_done(tutorial_lesson const &Lesson) const
+{
+ return false == Lesson.goals.empty() && std::ranges::all_of(Lesson.goals, [this](tutorial_lesson::goal const &Goal) { return m_first_steps_done[static_cast(Goal.step)]; });
+}
+
+void editor_mode::note_first_steps()
+{
if (ui()->mode() == nodebank_panel::TRACK)
first_step_done(first_step::tracks);
if (m_lay.active)
@@ -5856,160 +6248,67 @@ void editor_mode::render_first_steps()
first_step_done(first_step::gizmo);
if (m_track_gizmo_using || (m_point_drag.moved && m_track_point.valid() && false == editor_track::is_end(m_track_point.kind)))
first_step_done(first_step::vector);
- enum class trial { none, top, lay, turnout, select, profile, terrain, plan, trainset, signals };
- struct input
+ if (m_ride.active())
+ first_step_done(first_step::ride);
+}
+
+char const *editor_mode::tutorial_of_tool()
+{
+ auto const &lessons{tutorial_lessons()};
+ // the first of the lessons named whose steps aren't all reached yet
+ auto const undone = [&](std::initializer_list const Titles) {
+ for (auto const *title : Titles)
+ if (auto const found{std::ranges::find_if(lessons, [title](tutorial_lesson const &Lesson) { return std::string_view{title} == Lesson.title; })};
+ found != lessons.end() && false == tutorial_done(*found))
+ return title;
+ return "";
+ };
+ if (m_lay.active)
+ return undone({"Laying track", "Radius of the curves at the bends", "Curves", "Joining tracks"});
+ if (current_work_area() == work_area::terrain)
+ return undone({"Terrain from the terrain model"});
+ if (ui()->mode() != nodebank_panel::TRACK)
+ return "";
+ switch (m_track_tab)
{
- char const *keys;
- char const *text;
+ case track_tab::turnout:
+ return undone({m_switch_designer.open ? "Switch templates" : "Switches"});
+ case track_tab::profile:
+ return undone({"The grade line"});
+ case track_tab::route:
+ case track_tab::straights:
+ return undone({"Correcting a curve"});
+ case track_tab::signals:
+ case track_tab::kilometrage:
+ return undone({"Signals and posts"});
+ case track_tab::station:
+ case track_tab::station_signals:
+ case track_tab::line_block:
+ return undone({"A whole line, step by step"});
+ default:
+ return "";
+ }
+}
+
+void editor_mode::follow_tutorial()
+{
+ auto const &lessons{tutorial_lessons()};
+ auto const open_lesson = [&](std::string_view const Title) {
+ if (auto const found{std::ranges::find_if(lessons, [Title](tutorial_lesson const &Lesson) { return Title == Lesson.title; })}; found != lessons.end())
+ m_tutorial_page = static_cast(found - lessons.begin());
};
- struct goal
+ // the lesson of what's being done now, the next one once its steps are reached; opened when that changes, so a page turned by
+ // hand stays
+ if (auto const *followed{tutorial_of_tool()}; m_tutorial_followed != followed)
{
- first_step step;
- char const *text;
- };
- struct lesson
+ m_tutorial_followed = followed;
+ open_lesson(followed);
+ }
+ if (m_tutorial_goto != nullptr)
{
- char const *title;
- char const *clip;
- std::vector inputs;
- std::vector goals;
- trial action;
- void (*sketch)(ImDrawList &, ImVec2, ImVec2, double){nullptr};
- };
- static std::vector const lessons{
- {"Looking around",
- "camera",
- {{"RMB + move", "Hold the right button and move the mouse: look around"},
- {"RMB + W S A D", "With the right button held: fly forwards, back and to the sides; E and Q: up and down"},
- {"O", "The top view, and back to 3D"},
- {"wheel", "Zoom in and out where the cursor points"},
- {"MMB + move", "In the top view: hold the wheel and drag to move the map"},
- {"F", "Fly to what is selected"}},
- {{first_step::look, "Look around with the right button held"}, {first_step::top, "Switch to the top view"}},
- trial::top},
- {"Laying track",
- "lay",
- {{"F3", "The Tracks field of work"},
- {"L", "The lay tool"},
- {"LMB", "A click on the ground or on a free end: where the track starts"},
- {"LMB", "Each next click: a bend of the line, the curve at it made by itself. The line shown isn't a track yet"},
- {"Enter", "Lays the track clicked; to go on from its end, click the end"},
- {"Backspace", "Takes the last point back"},
- {"Esc", "Ends laying; the points not laid yet go only with the second Esc"}},
- {{first_step::tracks, "Open the Tracks field of work"}, {first_step::lay, "Turn the lay tool on"}, {first_step::laid, "Click a few points and lay them with Enter"}},
- trial::lay},
- {"Curves",
- "curves",
- {{"LMB", "Click the bends of the line: each gets a curve as large as fits; one too sharp for the speed set in the panel has its label in orange"},
- {"Tab", "A curve seen on the photo: click points along its middle, the curve ending at the last one; one of two or three radii comes out a compound curve"},
- {"Alt", "Held: the direction turns in steps of 15 degrees, or to 1:9, 1:6.6... to a straight track it starts by or crosses"},
- {"0 1 2 3", "Type the length of the next straight, Enter puts the point"},
- {"wheel", "Alone it zooms, as everywhere"}},
- {{first_step::bend, "Lay a track with a bend in it"}, {first_step::trace, "Switch to tracing a curve with Tab"}},
- trial::lay},
- {"Correcting a curve",
- "plan",
- {{"G", "The plan tool: a click on a curve shows its design, the vertex and the radius to drag in the view"},
- {"LMB + move", "In the panel, the band of the curvature: drag the plateau of an arc up or down for its radius, each arc of a compound curve its own"},
- {"LMB + move", "Drag a ramp sideways: the transition curve gets longer or shorter"},
- {"wheel", "Over the band: the radius by 5%, a transition by 5 m"},
- {"LMB", "Apply to the scenery: the tracks are laid by the design"}},
- {{first_step::plan, "Open the plan of a curve"}, {first_step::plan_band, "Change the curve in the band"}, {first_step::plan_apply, "Apply it to the scenery"}},
- trial::plan},
- {"Joining tracks",
- "join",
- {{"LMB + move", "Press on a free end (a magenta ring) and drag: a new track goes out of it"},
- {"LMB", "Let go on another free end: a curve joins the two tracks"},
- {"Ctrl + wheel", "While over the other end: the radius of the joining curve"},
- {"Shift + wheel", "While over the other end: another way to join"}},
- {{first_step::join, "Join two free ends"}, {first_step::wheel, "Change the radius of the joining curve with Ctrl+wheel"}},
- trial::lay},
- {"Switches",
- "switch",
- {{"T", "The switch tool; at the top: what to place"},
- {"LMB", "Click a track: the one the switch goes into"},
- {"LMB + move", "Press on it and drag: along the direction, sideways the side; let go: the switch is laid"},
- {"LMB + move", "Connection: drag from a straight onto the other track; a crossover, a double one or scissors, as chosen at the top"},
- {"LMB + move", "Switch ladder: drag from the straight to the side the tracks go off to; the ones missing are laid with it"},
- {"Esc", "Back to selecting"}},
- {{first_step::turnout, "Put a switch into a track"}},
- trial::turnout},
- {"Signals and posts",
- nullptr,
- {{"I", "The signalling tool: click a type of signal in its Signals, from the templates of the scenery"},
- {"LMB", "A click by a track places the signal on that side"},
- {"LMB + move", "Press by the track and drag along it: the trains running that way see the signal"},
- {"LMB + move", "Drag a standing signal: it moves along its track"},
- {"B", "Objects along the track: the hectometre posts and the W17 markers of a whole line at once, and trainsets"}},
- {{first_step::signal, "Place a signal"}, {first_step::posts, "Place the hectometre posts of a line"}},
- trial::signals,
- tutorial_signal_sketch},
- {"Selecting and fixing",
- "edit",
- {{"Esc", "The select tool"},
- {"LMB", "Click a track: it is selected, with its ends"},
- {"LMB + move", "Drag an end: at a joint the neighbours follow, from a free end a new track goes out, with Ctrl the end moves"},
- {"RMB", "A click on a track: what can be done with it"},
- {"Del", "Deletes the selected"},
- {"Ctrl + Z", "Takes the last change back; Ctrl+Y brings it back again"},
- {"Q W E", "The gizmo, to move, turn or bend the track: the next lesson"}},
- {{first_step::select, "Select a track"}, {first_step::undo, "Take a change back"}},
- trial::select},
- {"Editing with the gizmo",
- "gizmo",
- {{"Q", "The gizmo on the selected track, hidden until then: arrows which move it"},
- {"W", "Rings which turn it: its direction, its grade and its cant; the tracks joined to it follow"},
- {"E", "Handles which lengthen it at its free end, the curve keeping its radius"},
- {"LMB + move", "With the gizmo out the control vectors are there too: drag one, the curve follows it"},
- {"LMB", "A click on a point of the track: the gizmo goes to it, that point alone is moved or turned"},
- {"Ctrl", "Held while dragging: the gizmo goes by its step"},
- {"Esc", "Releases the point; the arrow above the view hides the gizmo again"}},
- {{first_step::gizmo, "Bring out the gizmo with Q, W or E"}, {first_step::vector, "Bend a track by a control vector, or move it with the gizmo"}},
- trial::select},
- {"The grade line",
- nullptr,
- {{"P", "The profile tool: a click on a track opens the grade line of its whole line in the strip below"},
- {"Shift + LMB", "A click adds a track, a box from the empty ground takes the tracks in it: the route runs between the outermost of them"},
- {"LMB + move", "Drag a point of the grade line: the grades on both sides of it follow"},
- {"LMB LMB", "A double click on the line adds a point"},
- {"Del", "Removes the chosen point"},
- {"Ctrl + wheel", "Over the plot: the heights stretched, the grades seen better"},
- {"RMB + move", "Over the plot: the view moves along the line"}},
- {{first_step::profile, "Open the grade line of a track"}, {first_step::profile_point, "Move or add a point"}, {first_step::profile_apply, "Apply it: the tracks take its heights"}},
- trial::profile,
- tutorial_route_sketch},
- {"Terrain from the terrain model",
- nullptr,
- {{"L", "In a scenery begun from nothing the first L asks: the real terrain of the place, or the flat plane"},
- {"F5", "The Terrain field of work: the terrain model (NMT) is in its tool options"},
- {"1", "Location: where the scenery lies, a click on the map or the place typed"},
- {"2", "Load along the tracks, or around the camera: the model comes from geoportal.gov.pl"},
- {"3", "Tracks onto the terrain: the tracks not fitted yet go onto the model, the ones fitted stay; the terrain to some tracks only: select them, Terrain in the inspector"},
- {"Ctrl + Z", "Takes the changes back"}},
- {{first_step::terrain, "Open the Terrain field of work"}, {first_step::nmt, "Load terrain from the model"}},
- trial::terrain,
- tutorial_terrain_sketch},
- {"Sceneries made before",
- nullptr,
- {{"LMB", "A track of an include or of a file that isn't saved: the inspector says why it can't be changed"},
- {"T", "Switches laid before keep their shape; Replace the geometry with the template, under More settings of the switch, gives them the one of the catalogue"},
- {"P", "Grade lines kept by an older editor are read as they were kept"},
- {"Ctrl + S", "Only what changed is written: the other lines stay as they were, the comment lines of other tools too"}},
- {},
- trial::none},
- {"Saving and driving",
- nullptr,
- {{"Ctrl + S", "Saves the scenery"},
- {"LMB", "Trainset tool: a click on the track where the train stands"},
- {"LMB LMB", "A double click on a vehicle of the list puts it into the train; a click on a vehicle of the train moves it, turns it or takes it out"},
- {"LMB", "Place and drive: the train goes onto the track and the cab is yours"}},
- {{first_step::save, "Save the scenery"}, {first_step::drive, "Drive on the new track"}},
- trial::trainset,
- tutorial_trainset_sketch},
- };
- auto const done = [&](lesson const &Lesson) {
- return false == Lesson.goals.empty() && std::all_of(Lesson.goals.begin(), Lesson.goals.end(), [&](goal const &Goal) { return m_first_steps_done[static_cast(Goal.step)]; });
- };
+ open_lesson(m_tutorial_goto);
+ m_tutorial_goto = nullptr;
+ }
m_tutorial_page = std::clamp(m_tutorial_page, 0, static_cast(lessons.size()) - 1);
auto const &lesson{lessons[m_tutorial_page]};
if (lesson.clip == nullptr)
@@ -6019,6 +6318,20 @@ void editor_mode::render_first_steps()
m_tutorial_clip.open(path);
m_tutorial_since = ImGui::GetTime();
}
+}
+
+void editor_mode::render_first_steps()
+{
+ if (false == m_first_steps_open)
+ {
+ if (false == m_tutorial_clip.path().empty())
+ m_tutorial_clip.close();
+ return;
+ }
+ note_first_steps();
+ follow_tutorial();
+ auto const &lessons{tutorial_lessons()};
+ auto const &lesson{lessons[m_tutorial_page]};
auto const scale{Global.ui_scale};
ImGui::SetNextWindowPos(ImVec2(ImGui::GetIO().DisplaySize.x * 0.5f, ImGui::GetIO().DisplaySize.y * 0.5f), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
ImGui::SetNextWindowBgAlpha(1.0f);
@@ -6032,171 +6345,181 @@ void editor_mode::render_first_steps()
ImGui::TextDisabled(STR_C("Lesson %d of %d"), m_tutorial_page + 1, static_cast(lessons.size()));
ImGui::SameLine();
ImGui::TextColored(ImVec4(0.55f, 0.8f, 1.0f, 1.0f), "%s", STR_C(lesson.title));
- if (lesson.clip != nullptr && false == m_tutorial_clip.missing())
- {
- auto const height{width * 320.0f / 520.0f};
- if (auto const texture{m_tutorial_clip.texture(ImGui::GetTime() - m_tutorial_since)}; texture != 0)
- {
- ImGui::Image(static_cast(texture), ImVec2(width, width * m_tutorial_clip.height() / std::max(1, m_tutorial_clip.width())));
- if (ImGui::IsItemClicked())
- m_tutorial_since = ImGui::GetTime();
- if (ImGui::IsItemHovered())
- ImGui::SetTooltip("%s", STR_C("Click: play it from the start"));
- }
- else
- {
- auto const at{ImGui::GetCursorScreenPos()};
- ImGui::GetWindowDrawList()->AddRectFilled(at, ImVec2(at.x + width, at.y + height), ImGui::GetColorU32(ImGuiCol_FrameBg));
- ImGui::Dummy(ImVec2(width, height));
- }
- }
- if (lesson.sketch != nullptr)
- {
- auto const at{ImGui::GetCursorScreenPos()};
- ImVec2 const end{at.x + width, at.y + std::round(width * 0.36f)};
- auto *list{ImGui::GetWindowDrawList()};
- list->AddRectFilled(at, end, ImGui::GetColorU32(ImGuiCol_FrameBg), 4.0f);
- list->PushClipRect(at, end, true);
- lesson.sketch(*list, at, end, ImGui::GetTime());
- list->PopClipRect();
- ImGui::Dummy(ImVec2(width, end.y - at.y));
- }
- ImGui::SeparatorText(STR_C("Mouse and keys"));
- for (auto const &entry : lesson.inputs)
- tutorial_input(entry.keys, entry.text, 150.0f * scale);
- if (false == lesson.goals.empty())
- ImGui::SeparatorText(STR_C("Try it"));
- for (auto const &entry : lesson.goals)
- {
- bool const reached{m_first_steps_done[static_cast(entry.step)]};
- ImGui::TextColored(reached ? ImVec4(0.4f, 0.9f, 0.4f, 1.0f) : ImGui::GetStyleColorVec4(ImGuiCol_Text), "%s", reached ? "[x]" : "[ ]");
- ImGui::SameLine();
- if (reached)
- ImGui::TextDisabled("%s", STR_C(entry.text));
- else
- ImGui::TextWrapped("%s", STR_C(entry.text));
- }
- if (m_tutorial_page == 1 && ui()->mode() == nodebank_panel::TRACK && false == GfxRenderer->Mouse_Hit())
- ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), "%s", STR_C("No ground under the cursor: track goes onto the level 0 plane, drawn as a grid. Terrain: F5"));
- switch (lesson.action)
- {
- case trial::top:
- if (ImGui::Button(Global.EditorOrtho ? STR_C("3D view (O)") : STR_C("Top view, orthographic (O)")))
- toggle_ortho();
- break;
- case trial::profile:
- {
- auto const on{ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::profile};
- ImGui::BeginDisabled(on);
- if (ImGui::Button(STR_C("The profile tool (P)")))
- {
- choose_work_area(work_area::tracks);
- show_track_tab(track_tab::profile);
- }
- ImGui::EndDisabled();
- break;
- }
- case trial::signals:
- {
- ImGui::BeginDisabled(ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::srk);
- if (ImGui::Button(STR_C("The signalling tool (I)")))
- {
- choose_work_area(work_area::tracks);
- show_track_tab(track_tab::srk);
- }
- ImGui::EndDisabled();
- break;
- }
- case trial::trainset:
- {
- ImGui::BeginDisabled(ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::lineside && m_vehicle.tab().open);
- if (ImGui::Button(STR_C("The trainset tool")))
- {
- choose_work_area(work_area::tracks);
- show_track_tab(track_tab::lineside);
- m_vehicle.tab().expand = true;
- }
- ImGui::EndDisabled();
- break;
- }
- case trial::plan:
- {
- ImGui::BeginDisabled(ui()->mode() == nodebank_panel::TRACK && (m_track_tab == track_tab::route || m_track_tab == track_tab::straights));
- if (ImGui::Button(STR_C("The plan tool (G)")))
- {
- choose_work_area(work_area::tracks);
- show_track_tab(track_tab::straights);
- }
- ImGui::EndDisabled();
- break;
- }
- case trial::terrain:
- {
- ImGui::BeginDisabled(current_work_area() == work_area::terrain);
- if (ImGui::Button(STR_C("Terrain (F5)")))
- choose_work_area(work_area::terrain);
- ImGui::EndDisabled();
- break;
- }
- case trial::lay:
- case trial::turnout:
- case trial::select:
- {
- auto const tab{lesson.action == trial::lay ? track_tab::lay : lesson.action == trial::turnout ? track_tab::turnout : track_tab::path};
- auto const on{ui()->mode() == nodebank_panel::TRACK && m_track_tab == tab};
- ImGui::BeginDisabled(on);
- if (ImGui::Button(lesson.action == trial::lay ? STR_C("Lay track (L)") : lesson.action == trial::turnout ? STR_C("The switch tool (T)") : STR_C("The select tool (Esc)")))
- {
- choose_work_area(work_area::tracks);
- show_track_tab(tab);
- }
- ImGui::EndDisabled();
- break;
- }
- default: break;
- }
+ render_tutorial_media(lesson, width);
+ render_tutorial_goals(lesson);
+ render_tutorial_trial(lesson);
ImGui::PopTextWrapPos();
ImGui::Separator();
- ImGui::BeginDisabled(m_tutorial_page == 0);
- if (ImGui::Button(STR_C("< Back")))
- --m_tutorial_page;
- ImGui::EndDisabled();
- ImGui::SameLine();
- auto const dot{ImGui::GetFrameHeight()};
- for (int index = 0; index < static_cast(lessons.size()); ++index)
- {
- ImGui::PushID(index);
- auto const at{ImGui::GetCursorScreenPos()};
- if (ImGui::InvisibleButton("##lesson", ImVec2(dot * 0.8f, dot)))
- m_tutorial_page = index;
- if (ImGui::IsItemHovered())
- ImGui::SetTooltip("%s", STR_C(lessons[index].title));
- ImVec2 const centre{at.x + dot * 0.4f, at.y + dot * 0.5f};
- auto const colour{done(lessons[index]) ? IM_COL32(100, 230, 100, 255) : ImGui::GetColorU32(ImGuiCol_TextDisabled)};
- if (index == m_tutorial_page)
- ImGui::GetWindowDrawList()->AddCircle(centre, dot * 0.3f, kGestureLit, 0, 2.0f);
- ImGui::GetWindowDrawList()->AddCircleFilled(centre, dot * 0.17f, colour);
- ImGui::PopID();
- ImGui::SameLine(0.0f, 0.0f);
- }
- ImGui::SameLine();
- if (m_tutorial_page + 1 < static_cast(lessons.size()))
- {
- if (ImGui::Button(STR_C("Next >")))
- ++m_tutorial_page;
- }
- else if (ImGui::Button(STR_C("Close")))
- m_first_steps_open = false;
- bool show{EditorSettings.first_steps()};
- if (ImGui::Checkbox(STR_C("Show when the editor opens"), &show))
- {
- EditorSettings.first_steps(show);
- EditorSettings.save();
- }
+ render_tutorial_pages();
}
ImGui::End();
}
+void editor_mode::render_tutorial_media(tutorial_lesson const &Lesson, float const Width)
+{
+ if (Lesson.clip != nullptr && false == m_tutorial_clip.missing())
+ {
+ // the room of a clip still loading, as the clips are recorded: 520 x 325
+ auto const height{Width * 325.0f / 520.0f};
+ if (auto const texture{m_tutorial_clip.texture(ImGui::GetTime() - m_tutorial_since)}; texture != 0)
+ {
+ auto const shown{Width * static_cast(m_tutorial_clip.height()) / static_cast(std::max(1, m_tutorial_clip.width()))};
+ ImGui::Image(static_cast(texture), ImVec2(Width, shown));
+ if (ImGui::IsItemClicked())
+ m_tutorial_since = ImGui::GetTime();
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("%s", STR_C("Click: play it from the start"));
+ }
+ else
+ {
+ auto const at{ImGui::GetCursorScreenPos()};
+ ImGui::GetWindowDrawList()->AddRectFilled(at, ImVec2(at.x + Width, at.y + height), ImGui::GetColorU32(ImGuiCol_FrameBg));
+ ImGui::Dummy(ImVec2(Width, height));
+ }
+ }
+ if (Lesson.sketch != nullptr)
+ {
+ auto const at{ImGui::GetCursorScreenPos()};
+ ImVec2 const end{at.x + Width, at.y + std::round(Width * 0.36f)};
+ auto *list{ImGui::GetWindowDrawList()};
+ list->AddRectFilled(at, end, ImGui::GetColorU32(ImGuiCol_FrameBg), 4.0f);
+ list->PushClipRect(at, end, true);
+ Lesson.sketch(*list, at, end, ImGui::GetTime());
+ list->PopClipRect();
+ ImGui::Dummy(ImVec2(Width, end.y - at.y));
+ }
+}
+
+void editor_mode::render_tutorial_goals(tutorial_lesson const &Lesson)
+{
+ ImGui::SeparatorText(STR_C("Mouse and keys"));
+ for (auto const &entry : Lesson.inputs)
+ tutorial_input(entry.keys, entry.text, 150.0f * Global.ui_scale);
+ if (false == Lesson.goals.empty())
+ ImGui::SeparatorText(STR_C("Try it"));
+ for (auto const &entry : Lesson.goals)
+ {
+ bool const reached{m_first_steps_done[static_cast(entry.step)]};
+ ImGui::TextColored(reached ? ImVec4(0.4f, 0.9f, 0.4f, 1.0f) : ImGui::GetStyleColorVec4(ImGuiCol_Text), "%s", reached ? "[x]" : "[ ]");
+ ImGui::SameLine();
+ if (reached)
+ ImGui::TextDisabled("%s", STR_C(entry.text));
+ else
+ ImGui::TextWrapped("%s", STR_C(entry.text));
+ }
+ if (Lesson.action == tutorial_lesson::trial::lay && ui()->mode() == nodebank_panel::TRACK && false == GfxRenderer->Mouse_Hit())
+ ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), "%s", STR_C("There is no ground under the mouse: the track will lie flat at height 0. Real ground: F5"));
+}
+
+void editor_mode::render_tutorial_trial(tutorial_lesson const &Lesson)
+{
+ using trial = tutorial_lesson::trial;
+ if (Lesson.action == trial::top)
+ {
+ if (ImGui::Button(Global.EditorOrtho ? STR_C("3D view (O)") : STR_C("Top view, orthographic (O)")))
+ toggle_ortho();
+ return;
+ }
+ if (Lesson.action == trial::terrain)
+ {
+ ImGui::BeginDisabled(current_work_area() == work_area::terrain);
+ if (ImGui::Button(STR_C("Terrain (F5)")))
+ choose_work_area(work_area::terrain);
+ ImGui::EndDisabled();
+ return;
+ }
+ // a tool of Tracks: the tab its button opens, and the one beside it which counts as that tool open as well
+ struct tool_button
+ {
+ char const *label;
+ track_tab tab;
+ track_tab also;
+ };
+ tool_button button{};
+ switch (Lesson.action)
+ {
+ case trial::lay:
+ button = {STR_C("Lay track (L)"), track_tab::lay, track_tab::lay};
+ break;
+ case trial::turnout:
+ button = {STR_C("The switch tool (T)"), track_tab::turnout, track_tab::turnout};
+ break;
+ case trial::select:
+ button = {STR_C("The select tool (Esc)"), track_tab::path, track_tab::path};
+ break;
+ case trial::profile:
+ button = {STR_C("The profile tool (P)"), track_tab::profile, track_tab::profile};
+ break;
+ case trial::signals:
+ button = {STR_C("The signals tool (I)"), track_tab::signals, track_tab::signals};
+ break;
+ case trial::station:
+ button = {STR_C("The station tool"), track_tab::station, track_tab::station_signals};
+ break;
+ case trial::plan:
+ button = {STR_C("The plan tool (G)"), track_tab::straights, track_tab::route};
+ break;
+ case trial::trainset:
+ button = {STR_C("The trainset tool"), track_tab::lineside, track_tab::lineside};
+ break;
+ default:
+ return;
+ }
+ // the trainset tool is open only with its part of the tab expanded
+ auto const in_use{ui()->mode() == nodebank_panel::TRACK && (m_track_tab == button.tab || m_track_tab == button.also) && (Lesson.action != trial::trainset || m_vehicle.tab().open)};
+ ImGui::BeginDisabled(in_use);
+ if (ImGui::Button(button.label))
+ {
+ choose_work_area(work_area::tracks);
+ show_track_tab(button.tab);
+ if (Lesson.action == trial::trainset)
+ m_vehicle.tab().expand = true;
+ }
+ ImGui::EndDisabled();
+}
+
+void editor_mode::render_tutorial_pages()
+{
+ auto const &lessons{tutorial_lessons()};
+ auto const count{static_cast(lessons.size())};
+ ImGui::BeginDisabled(m_tutorial_page == 0);
+ if (ImGui::Button(STR_C("< Back")))
+ --m_tutorial_page;
+ ImGui::EndDisabled();
+ ImGui::SameLine();
+ auto const dot{ImGui::GetFrameHeight()};
+ for (int index = 0; index < count; ++index)
+ {
+ ImGui::PushID(index);
+ auto const at{ImGui::GetCursorScreenPos()};
+ if (ImGui::InvisibleButton("##lesson", ImVec2(dot * 0.8f, dot)))
+ m_tutorial_page = index;
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("%s", STR_C(lessons[index].title));
+ ImVec2 const centre{at.x + dot * 0.4f, at.y + dot * 0.5f};
+ auto const colour{tutorial_done(lessons[index]) ? IM_COL32(100, 230, 100, 255) : ImGui::GetColorU32(ImGuiCol_TextDisabled)};
+ if (index == m_tutorial_page)
+ ImGui::GetWindowDrawList()->AddCircle(centre, dot * 0.3f, kGestureLit, 0, 2.0f);
+ ImGui::GetWindowDrawList()->AddCircleFilled(centre, dot * 0.17f, colour);
+ ImGui::PopID();
+ ImGui::SameLine(0.0f, 0.0f);
+ }
+ ImGui::SameLine();
+ if (m_tutorial_page + 1 < count)
+ {
+ if (ImGui::Button(STR_C("Next >")))
+ ++m_tutorial_page;
+ }
+ else if (ImGui::Button(STR_C("Close")))
+ m_first_steps_open = false;
+ bool show{EditorSettings.first_steps()};
+ if (ImGui::Checkbox(STR_C("Show when the editor opens"), &show))
+ {
+ EditorSettings.first_steps(show);
+ EditorSettings.save();
+ }
+}
+
void editor_mode::render_shortcuts_window()
{
if (false == m_shortcuts_open)
@@ -6229,6 +6552,13 @@ void editor_mode::render_shortcuts_window()
{"RMB held, E / Q", "Fly up / down (Page Up / Page Down in the legacy scheme)"},
{"F", "Fly to the selected"},
{"O", "Top view, orthographic"}}},
+ {"Ride along the track",
+ {{"Y", "Ride along the track under the cursor, the tools working on; Y again leaves"},
+ {"RMB held, W / S", "Drive; Shift faster, Ctrl+W / Ctrl+Down much faster"},
+ {"RMB held, A / D", "Next track on the left / right"},
+ {"Z", "The way at the next switch (it isn't thrown)"},
+ {"RMB held, E / Q; wheel", "Higher / lower"},
+ {"Ctrl+M", "Minimap, stations by their W4"}}},
{"Gizmo",
{{"Q / W / E", "Translate / rotate / scale; in the tracks they bring the hidden gizmo out"},
{"R", "Local space"},
@@ -6250,7 +6580,7 @@ void editor_mode::render_shortcuts_window()
{"L / T / U", "Lay track / switch / turntable"},
{"H", "Throw the selected switch over to its other path, in the editor only"},
{"G (C)", "Plan: a straight, its ends and the middle; a curve, its vertex and radius"},
- {"I / B", "Signalling / objects along the track"},
+ {"I / X / B", "Signals / kilometrage / posts along the track"},
{"P / V / J", "Profile / speed / joints"},
{"Ctrl+F", "Find a track by its name"},
{"Shift+LMB", "Add a track to the selection, drag: a box"},
@@ -6375,7 +6705,7 @@ void editor_mode::render_gizmo_options()
ImGui::SameLine();
render_top_tracks_choice(true);
}
- if (ui()->mode() == nodebank_panel::TRACK && m_track_tab != track_tab::path && m_track_tab != track_tab::turnout && m_track_tab != track_tab::turntable && m_track_tab != track_tab::srk &&
+ if (ui()->mode() == nodebank_panel::TRACK && m_track_tab != track_tab::path && m_track_tab != track_tab::turnout && m_track_tab != track_tab::turntable && m_track_tab != track_tab::signals &&
m_track_tab != track_tab::lineside)
return;
auto &enabled{ui()->mode() == nodebank_panel::TRACK ? m_track_gizmo_on : m_gizmo_enabled};
@@ -6608,11 +6938,16 @@ void editor_mode::render_include_gizmo(glm::mat4 const &View, glm::mat4 const &P
if (positions == 0)
return; // nothing tells where the include is
- // only the axes the template has parameters for can be manipulated
+ // only the axes the template has parameters for can be manipulated. a signal stands on the ground by its track: it is moved in
+ // the plan, at the height it has
+ // not waited for: a scan started again while a signal is selected would stop the editor for its whole length
+ if (m_include.info.category == "signal")
+ signal_scan(false);
+ auto const signal{signal_template_of(m_include.target) != nullptr};
auto operation = 0;
for (auto axis = 0; axis < 3; ++axis)
{
- if (m_gizmo_op == gizmo_operation::translate && position[axis] >= 0)
+ if (m_gizmo_op == gizmo_operation::translate && position[axis] >= 0 && false == (signal && axis == 1))
operation |= (ImGuizmo::TRANSLATE_X << axis);
else if (m_gizmo_op == gizmo_operation::rotate && rotation[axis] >= 0)
operation |= (ImGuizmo::ROTATE_X << axis);
@@ -6637,14 +6972,18 @@ void editor_mode::render_include_gizmo(glm::mat4 const &View, glm::mat4 const &P
// in the signal tool a press on the mast drags the signal along its track: the gizmo, whose up axis runs along the
// mast, gives way over a signal and while one is dragged
- auto const yield{ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::srk && false == ImGuizmo::IsUsing() && (m_signal.moving || m_signal.placing || signal_hit() >= 0)};
+ auto const yield{ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::signals && false == ImGuizmo::IsUsing() && (m_signal.moving || m_signal.placing || signal_hit() >= 0)};
ImGuizmo::Enable(false == yield);
ImGuizmo::Manipulate(glm::value_ptr(View), glm::value_ptr(Projection), static_cast(operation), mode, glm::value_ptr(matrix), nullptr, snap);
ImGuizmo::Enable(true);
if (false == ImGuizmo::IsUsing())
+ {
+ signal_gizmo_end();
return;
+ }
m_gizmo_using = true;
+ signal_gizmo_begin();
float newtranslation[3], newrotation[3], newscale[3];
ImGuizmo::DecomposeMatrixToComponents(glm::value_ptr(matrix), newtranslation, newrotation, newscale);
@@ -6674,6 +7013,7 @@ void editor_mode::render_include_gizmo(glm::mat4 const &View, glm::mat4 const &P
}
}
apply_include();
+ signal_gizmo_step();
}
glm::mat4 editor_mode::projection_matrix(float const Aspect)
@@ -6688,10 +7028,13 @@ glm::mat4 editor_mode::projection_matrix(float const Aspect)
void editor_mode::toggle_ortho()
{
+ // the view from above isn't one from the track, the ride ends
+ m_ride.leave();
Global.EditorOrtho = !Global.EditorOrtho;
+ // either way: a scenery made in the wizard opens seen from above already
+ first_step_done(first_step::top);
if (Global.EditorOrtho)
{
- first_step_done(first_step::top);
m_ortho_pitch = Camera.Angle.x;
Camera.Angle.x = -M_PI_2;
Camera.Angle.z = 0.0;
@@ -6700,6 +7043,7 @@ void editor_mode::toggle_ortho()
{
Camera.Angle.x = m_ortho_pitch;
ortho_pan_stop();
+ camera_above_ground();
}
}
@@ -6711,8 +7055,11 @@ void editor_mode::ortho_pan_to(double const Horizontal, double const Vertical)
auto const dx{Horizontal - m_ortho_pan_cursor.x};
auto const dy{Vertical - m_ortho_pan_cursor.y};
m_ortho_pan_cursor = {Horizontal, Vertical};
- auto const scale{2.0 * static_cast(Global.EditorOrthoExtent) / static_cast(io.DisplaySize.y)};
- auto const world{RotateY(glm::dvec3{dx * scale, 0.0, dy * scale}, static_cast(Camera.Angle.y))};
+ auto const scale{Global.EditorOrtho ? 2.0 * static_cast(Global.EditorOrthoExtent) / static_cast(io.DisplaySize.y) : m_pan_metres};
+ // looked at from the side, a pixel up the screen is more of the ground than one across
+ auto const along{Global.EditorOrtho ? 1.0 : 1.0 / std::max(0.25, std::abs(std::sin(static_cast(Camera.Angle.x))))};
+ auto const world{RotateY(glm::dvec3{dx * scale, 0.0, dy * scale * along}, static_cast(Camera.Angle.y))};
+ m_ride.leave();
Camera.Pos.x -= world.x;
Camera.Pos.z -= world.z;
Camera.Velocity = {};
@@ -6729,6 +7076,13 @@ void editor_mode::on_scroll(double const Xoffset, double const Yoffset)
{
if (false == ImGui::GetIO().WantCaptureMouse && track_wheel(Yoffset != 0.0 ? Yoffset : Xoffset))
return;
+ // riding along the track the wheel the tools left raises and lowers the camera over the rails
+ if (m_ride.active())
+ {
+ if (false == ImGui::GetIO().WantCaptureMouse && Yoffset != 0.0)
+ m_ride.wheel(std::clamp(Yoffset, -2.0, 2.0));
+ return;
+ }
// a swipe on a touchpad goes on after the cursor left the window, with no place for the ray under it
if (ImGui::GetIO().WantCaptureMouse || Yoffset == 0.0 || false == ImGui::IsMousePosValid())
return;
@@ -6784,6 +7138,12 @@ void editor_mode::update_camera(double const Deltatime)
Camera.Angle.x = -M_PI_2;
Camera.Angle.z = 0.0;
}
+ // riding along the track the camera goes where the track takes it, a framing doesn't fly it off
+ if (m_ride.active())
+ {
+ m_focus_active = false;
+ m_ride.advance(Camera, Deltatime, m_input.mouse.button(GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS);
+ }
// focus animation runs after Camera.Update() so it overrides any residual velocity/rotation;
// it smoothly drives both position and orientation toward the framed object
@@ -6837,11 +7197,41 @@ void editor_mode::update_camera(double const Deltatime)
Global.pCamera = Camera;
}
+glm::dvec3 editor_mode::camera_look() const
+{
+ return {-std::sin(Camera.Angle.y), 0.0, -std::cos(Camera.Angle.y)};
+}
+
+void editor_mode::ride_enter()
+{
+ // the track under the cursor, else the one nearest the ground under it, else the one nearest the camera
+ auto under{track_under_cursor(nullptr, 30.0f)};
+ auto *track{under.track};
+ auto path{under.path};
+ auto point{under.point};
+ if (track == nullptr && ImGui::IsMousePosValid())
+ {
+ point = std::as_const(*this).cursor_ground();
+ track = kilometrage::track_near(point, 30.0, path);
+ }
+ if (track == nullptr)
+ {
+ point = Camera.Pos;
+ track = kilometrage::track_near(point, 200.0, path);
+ }
+ if (false == m_ride.enter(track, path, point, camera_look(), true))
+ ui()->set_status(STR_C("No track nearby"), true);
+}
+
void editor_mode::enter()
{
m_statebackup = {Global.pCamera, FreeFlyModeFlag, Global.ControlPicking};
// the editor changes the tracks, their sleepers are worked out as they're needed
track_sleepers::lay_in_background(false);
+ // the editor may remove the tracks and the vehicles the recording refers to: it ends here
+ simulation::Blackbox.close();
+ // the cursor drawn into the picture is the editor's: back on when it comes back, if it was chosen
+ ui_layer::draw_cursor(m_draw_cursor);
if (simulation::Region != nullptr)
{
@@ -6939,7 +7329,10 @@ void editor_mode::enter()
void editor_mode::exit()
{
+ m_ride.leave();
track_sleepers::lay_in_background(true);
+ // the driver's view has no menu to switch the drawn cursor off: the system one there
+ ui_layer::draw_cursor(false);
Global.editor_tracks = false;
EditorModeFlag = false;
Global.ControlPicking = m_statebackup.picking;
@@ -7085,6 +7478,27 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in
if (!anyModifier && m_userinterface->on_key(Key, Action))
return;
+ // riding along the track the keys drive the camera; Y starts the ride on the track under the cursor
+ if (false == ImGui::GetIO().WantTextInput)
+ {
+ std::string status;
+ auto const taken{m_ride.key(Key, Action, Mods, camera_look(), m_input.mouse.button(GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS, status)};
+ if (false == status.empty())
+ ui()->set_status(status, m_ride.active());
+ if (taken)
+ {
+ // the right button held to drive isn't a click for the menu of the track under the cursor
+ m_track_context.armed = false;
+ return;
+ }
+ // not with a button held: a drag going on would lose its release to the ride
+ if (Key == GLFW_KEY_Y && Action == GLFW_PRESS && false == anyModifier && false == m_ride.active() && m_input.mouse.button(GLFW_MOUSE_BUTTON_RIGHT) != GLFW_PRESS && m_input.mouse.button(GLFW_MOUSE_BUTTON_LEFT) != GLFW_PRESS)
+ {
+ ride_enter();
+ return;
+ }
+ }
+
if (ui()->mode() == nodebank_panel::TRACK && is_press(Action) && (Mods & (GLFW_MOD_CONTROL | GLFW_MOD_ALT)) == 0 && typed_key(Key))
return;
@@ -7129,6 +7543,14 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in
return;
}
+ // the minimap with the stations
+ if (Global.ctrlState && false == Global.shiftState && Key == GLFW_KEY_M)
+ {
+ if (is_press(Action))
+ m_minimap.toggle();
+ return;
+ }
+
// all docks unpinned and hidden at the edges, for the most of the view, or pinned back
if (Global.ctrlState && false == Global.shiftState && Key == GLFW_KEY_SPACE)
{
@@ -7167,12 +7589,12 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in
if (from != nullptr)
copy_track_style(*from);
else
- ui()->set_status(STR_C("Select one track, or point at one, to copy its properties"), true);
+ ui()->set_status(STR_C("Select one track, or point at one, to take its properties"), true);
}
else if (m_track_style.values.empty())
- ui()->set_status(STR_C("Copy the properties of a track first: Ctrl+Shift+C"), true);
+ ui()->set_status(STR_C("Take the properties of a track first: Ctrl+Shift+C"), true);
else if (tracks.empty())
- ui()->set_status(STR_C("Select the tracks to paste the properties on"), true);
+ ui()->set_status(STR_C("Select the tracks to set the properties on"), true);
else
paste_track_style(tracks);
}
@@ -7205,7 +7627,7 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in
return;
// shortcuts: undo/redo. not in the middle of a drag, it would go on from the state which was undone
- if (Global.ctrlState && (Key == GLFW_KEY_Z || Key == GLFW_KEY_Y) && is_press(Action) && (m_track_gizmo_using || m_track_set_using || m_straights.dragging || m_extend.active || m_switch.placing || m_point_drag.active || m_handle_drag.active))
+ if (Global.ctrlState && (Key == GLFW_KEY_Z || Key == GLFW_KEY_Y) && is_press(Action) && (m_track_gizmo_using || m_track_set_using || m_straights.dragging || m_extend.active || m_switch.placing || m_point_drag.active || m_handle_drag.active || m_roadtool.lifting))
return;
if (Global.ctrlState && Key == GLFW_KEY_Z && is_press(Action))
{
@@ -7257,6 +7679,12 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in
// an open list or menu takes this Esc for itself, the selection behind it stays
if (ImGui::IsPopupOpen("", ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel))
break;
+ // the switch being clicked off the view given up
+ if (is_press(Action) && m_switch_designer.open && m_switch_designer.picking)
+ {
+ m_switch_designer.picking = false;
+ break;
+ }
// the download area being drawn given up, the one before stays
if (is_press(Action) && m_area_drawing.active)
{
@@ -7278,12 +7706,16 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in
lay_escape();
else if (m_track_style.picking)
m_track_style.picking = false;
+ else if (m_profile.picking)
+ m_profile.picking = false;
else if (track_busy())
{
cancel_track_tools();
m_straights.tool = 0;
}
- else if (m_track_tab == track_tab::srk && m_signal.armed)
+ else if (m_track_tab == track_tab::signals && m_signal.picking_read)
+ m_signal.picking_read = false;
+ else if (m_track_tab == track_tab::signals && m_signal.armed)
m_signal.armed = false;
else if (m_track_tab == track_tab::path && m_track_set.size() >= 2)
select_tracks({});
@@ -7311,6 +7743,16 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in
break;
case GLFW_KEY_BACKSPACE:
+ // the switch being clicked off the view: the last point taken back
+ if (m_switch_designer.open && m_switch_designer.picking)
+ {
+ if (is_press(Action) && false == m_switch_designer.clicks.empty())
+ {
+ m_switch_designer.clicks.pop_back();
+ switch_designer_measure();
+ }
+ break;
+ }
// the download area: the last point taken back
if (is_press(Action) && m_area_drawing.active)
{
@@ -7399,6 +7841,16 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const
return;
}
+ // a switch being clicked off the view for the template editor takes the left button
+ if (m_switch_designer.open && m_switch_designer.picking && Button == GLFW_MOUSE_BUTTON_LEFT)
+ {
+ // on the terrain under the cursor, then on the level of the first point: no track or ballast in the view catches the point
+ if (is_press(Action))
+ switch_designer_click(m_switch_designer.clicks.empty() ? cursor_terrain(std::as_const(*this).cursor_ground().y) : cursor_level(m_switch_designer.clicks.front().y));
+ m_input.mouse.button(Button, Action);
+ return;
+ }
+
// the download area drawn on the map takes the left button while it's drawn
if (m_area_drawing.active && Button == GLFW_MOUSE_BUTTON_LEFT)
{
@@ -7439,6 +7891,18 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const
// with the road window open the left button works its tools, whichever edit mode is on but the track one
if (m_roadtool.window && Button == GLFW_MOUSE_BUTTON_LEFT && ui()->mode() != nodebank_panel::TRACK)
{
+ // Alt+LMB on a point: its height (and the other selected ones') dragged up or down
+ if (is_press(Action) && Global.altState && false == ImGui::GetIO().WantCaptureMouse && road_lift_start())
+ {
+ m_input.mouse.button(Button, Action);
+ return;
+ }
+ if (false == is_press(Action) && m_roadtool.lifting)
+ {
+ road_lift_finish();
+ m_input.mouse.button(Button, Action);
+ return;
+ }
if (is_press(Action))
{
// NOTE: the pick is resolved a few frames later, by then it's known whether the press was meant for the UI
@@ -7673,7 +8137,7 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const
// game-engine style look: hide & grab the cursor while flying, restore it on release
Application.set_cursor(is_press(Action) ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL);
}
- else if (Button == GLFW_MOUSE_BUTTON_MIDDLE && Global.EditorOrtho)
+ else if (Button == GLFW_MOUSE_BUTTON_MIDDLE)
{
if (is_press(Action))
{
@@ -7681,6 +8145,17 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const
m_ortho_pan_cursor = m_input.mouse.position();
m_focus_active = false;
Camera.Velocity = {};
+ // in the perspective view the ground under the cursor goes along with it: metres of it to a pixel there, as far as it is
+ m_pan_metres = 0.0;
+ if (false == Global.EditorOrtho)
+ {
+ auto const &io{ImGui::GetIO()};
+ auto const distance{glm::length(GfxRenderer->Mouse_Position())};
+ if (GfxRenderer->Mouse_Hit() && io.DisplaySize.y > 0.0f && distance > 0.5 && distance < 20000.0)
+ m_pan_metres = 2.0 * distance * std::tan(glm::radians(Global.FieldOfView / Global.ZoomFactor) * 0.5) / static_cast(io.DisplaySize.y);
+ else
+ m_ortho_pan = false; // nothing under the cursor to hold
+ }
}
else if (is_release(Action))
ortho_pan_stop();
@@ -7776,7 +8251,9 @@ void editor_mode::on_event_poll()
bool const flying = m_input.mouse.button(GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS;
if (flying)
{
- m_input.poll();
+ // riding along the track the camera only looks around, the keys drive the ride
+ if (false == m_ride.active())
+ m_input.poll();
first_step_done(first_step::look);
}
else if (m_camera_flying)
diff --git a/application/editormode.h b/application/editormode.h
index 38d51286e..60da345e4 100644
--- a/application/editormode.h
+++ b/application/editormode.h
@@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/.
#include "input/editorkeyboardinput.h"
#include "vehicle/Camera.h"
#include "application/editormodegauge.h"
+#include "application/editormoderide.h"
+#include "application/editormodeminimap.h"
#include "application/editormodejoints.h"
#include "application/editormodelineside.h"
#include "application/editormodeparallel.h"
@@ -31,6 +33,7 @@ http://mozilla.org/MPL/2.0/.
#include "editor/editorNmt.hpp"
#include "editor/editorGeoMap.hpp"
#include "editor/editorTrack.hpp"
+#include "editor/editorTrackTrace.hpp"
#include "editor/editorConnections.hpp"
#include "editor/editorAlignment.hpp"
#include "editor/editorAlignmentStore.hpp"
@@ -60,6 +63,7 @@ http://mozilla.org/MPL/2.0/.
#include
#include
#include
+#include
#include
class TAnimModel;
@@ -168,6 +172,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri
std::vector profile_library;
std::optional> alignments; // the kept horizontal alignments changed too, these were the ones before
std::optional> switch_records; // the kept switches changed too, these were the ones before
+ std::optional hand_joints; // the joints of a station put by hand changed too, these were the ones before
std::optional kilometrage; // the kilometrage before the change (Action::Kilometrage)
std::vector copies; // models an array added to the one it was made of
bool joined{false}; // undone and redone together with the change before it
@@ -186,6 +191,10 @@ class editor_mode : public application_mode, private editor_track::observer, pri
int m_track_edits{0};
// methods
void update_camera(double const Deltatime);
+ // the camera onto the track under the cursor, or the nearest one, to ride along it
+ void ride_enter();
+ // the way the camera looks, in the plan
+ glm::dvec3 camera_look() const;
editor_ui *ui() const;
void redo_last();
@@ -233,6 +242,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri
bool m_dragging = false;
glm::dvec3 oldPos; // world position of the last brush placement
bool m_brush_has_last{false}; // false at the start of a brush stroke, so the first placement ignores spacing
+ bool m_draw_cursor{false}; // the cursor drawn into the picture (View menu), on only while the editor is
bool mouseHold{false};
float kMaxPlacementDistance = 200.0f;
static bool m_change_history;
@@ -241,6 +251,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri
double m_ortho_pitch{0.0};
bool m_ortho_pan{false};
glm::dvec2 m_ortho_pan_cursor{0.0};
+ double m_pan_metres{0.0}; // of the ground to a pixel, held by the panning in the perspective view
void ortho_pan_to(double const Horizontal, double const Vertical);
void ortho_pan_stop();
// camera fly-mode (right mouse button held); used to flush motion when it's released
@@ -253,6 +264,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri
glm::dvec3 clamp_mouse_offset_to_max(const glm::dvec3 &offset);
// the ground under a point the cursor landed on, for things which are to stand on the ground
glm::dvec3 placement_on_ground(glm::dvec3 Location) override;
+ // the ground under a point, the point itself with none there
+ glm::dvec3 ground_at(glm::dvec3 Location) const;
// puts every instance of the model the selected node shows on the ground under it
void drop_model_instances();
void render_object_menu();
@@ -263,11 +276,31 @@ class editor_mode : public application_mode, private editor_track::observer, pri
void render_shortcuts_window();
bool m_shortcuts_open{false};
using first_step = editor_first_step;
+ // the tutorial: a window of lessons, each with a clip or a sketch, the mouse and the keys it teaches and the steps to try
+ struct tutorial_lesson;
+ static std::vector const &tutorial_lessons();
+ // a lesson is done once all its steps are
+ bool tutorial_done(tutorial_lesson const &Lesson) const;
void render_first_steps();
+ // the steps reached by what the editor is doing now
+ void note_first_steps();
+ // the lesson of the tool in use: the first of its lessons not done yet, or none
+ char const *tutorial_of_tool();
+ // the lesson the tool in use or a button of a panel asks for opened, and the clip of the lesson open loaded
+ void follow_tutorial();
+ void render_tutorial_media(tutorial_lesson const &Lesson, float const Width);
+ void render_tutorial_goals(tutorial_lesson const &Lesson);
+ // the button under a lesson, opening the tool it's about or switching the view
+ void render_tutorial_trial(tutorial_lesson const &Lesson);
+ // the buttons to the lesson before and after, and a dot for each lesson, green when it's done
+ void render_tutorial_pages();
void first_step_done(first_step const Step) override;
+ void open_kilometrage() override;
bool m_first_steps_open{false};
std::array(first_step::count)> m_first_steps_done{};
int m_tutorial_page{0};
+ char const *m_tutorial_goto{nullptr}; // the lesson of this title opened by a button of a panel
+ std::string m_tutorial_followed; // the lesson the tool in use asked for last: it's opened when that changes
double m_tutorial_since{0.0};
editor_clips::clip m_tutorial_clip;
// deletes what's selected: a road piece or point, a signal, an include of a scenery template, a model, tracks (Del)
@@ -345,6 +378,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri
bool grown{false}; // the chunks waiting were all asked for by growing: the formations aren't made anew after them
bool reshape{false}; // the formations of the tracks laid anew once the chunks waiting are made, as the tracks are put onto the terrain
bool unfitted{false}; // the tracks put onto the terrain are only the ones whose grade line isn't fitted yet
+ bool redo_hand{false}; // all anew takes the grade lines edited by hand too
+ std::unordered_set stayed; // the tracks this putting onto the terrain leaves as they are
double grow_time{-10.0};
double slope{1.5};
double reach{60.0};
@@ -363,6 +398,31 @@ class editor_mode : public application_mode, private editor_track::observer, pri
std::size_t shaped{0};
std::string status;
std::string error;
+ bool common{true}; // the tracks nearly parallel under 5.1 m apart lie on one grade line
+ static int constexpr grade_line_own{-1};
+ static int constexpr grade_line_steep{-2};
+ static int constexpr grade_line_off{-3}; // taken off a grade line by hand, stays on its own when the lines are worked out again
+ static int constexpr grade_line_off_number{-10}; // this and below: taken off the grade line of this number less this
+ std::map grade_lines; // of each track the number of the grade line it shares, or one of those above
+ std::set grade_lines_hand; // the tracks put on their grade line by hand: they stay on it when the lines are worked out again
+ bool grade_lines_loaded{false};
+ bool grade_lines_dirty{false}; // the edits of the tracks carried their lines on: stored once, with the next frame
+ std::unordered_map grade_line_keys; // of the tracks changed, the key each had last, to carry its line on to the next
+ std::vector> grade_line_replaced; // the first paths of the tracks of a line changed since the last frame: a new track on one takes its line
+ std::unordered_set on_hump; // the tracks of the humps fitted to the model: no grade line shared levels them
+ std::size_t grade_lines_changes{0};
+ std::string explain; // a track whose run the next sharing of the grade lines tells of in the log, for a selftest
+ struct surface_place
+ {
+ TTrack const *track;
+ int path;
+ double share;
+ int surface;
+ };
+ std::vector surface_places; // what lies on the surface of each group on common timbers
+ bool camera_check{false}; // chunks were made: the 3d camera may be under them now
+ std::vector buried; // the tracks just laid, when a part of them is hidden in the ground
+ double buried_length{0.0}; // m of them hidden
// the tracks of a scenery built at any height put onto the terrain model: the model offset to meet the scenery, then the grade
// line of each line of tracks fitted to the model, the longest first, then the terrain made along them
enum class automatic
@@ -412,6 +472,28 @@ class editor_mode : public application_mode, private editor_track::observer, pri
std::size_t lines{0}; // grade lines fitted and applied
std::size_t refused{0}; // grade lines the checks didn't let apply
std::size_t departures{0}; // grade lines parting from the terrain model by much
+ // what the last putting of the tracks onto the terrain found, listed in the panel to be looked at: a line the checks
+ // refused, a line parting from the model by much, a path which didn't take its line
+ struct finding
+ {
+ enum class kind
+ {
+ refused,
+ off,
+ parted
+ };
+ kind what{kind::refused};
+ TTrack *from{nullptr}; // the ends of the line, for its profile
+ TTrack *to{nullptr};
+ double length{0.0};
+ glm::dvec3 where{0.0}; // the place to look at
+ std::string text;
+ double size{0.0}; // m the line or the path is off by: of one kind the worst told first
+ };
+ std::vector findings;
+ bool result{false}; // the putting onto the terrain ended: what it did is told in the panel until the next one
+ bool run{false}; // the tracks are being put onto the terrain, the chunks after the grade lines too: the steps told
+ std::size_t fetch_most{0}; // the most squares of the model waited for since the loading began, for its progress
// the terrain made under the tracks as they are: the model drawn to them by the difference found at the places along them,
// fading out away from them into the offset of the whole scenery
bool under{false};
@@ -455,6 +537,9 @@ class editor_mode : public application_mode, private editor_track::observer, pri
std::optional nmt_terrain_offset(std::vector const &Points, bool &Foreign) const;
// the same along the edges the chunk shares with the chunks beside it in memory
std::optional nmt_seam_offset(heightmap::chunk_key const &Key, bool &Foreign) const;
+ // the offset a chunk made from the model where there's no terrain gets: of the terrain made from the model beside it, empty
+ // (the offset of the scenery) beside terrain made by hand or none
+ std::optional nmt_chunk_offset(heightmap::chunk_key const &Key) const;
// the terrain beside the formation of the track is the one made from the model; Waiting: its squares of the model aren't in yet
// the tracks changed by hand are told to the terrain: their formations laid anew, of the tracks removed taken away, a
// track laid onto the terrain of the model given its own, once the mouse lets go; in the step of the history of the change
@@ -472,6 +557,9 @@ class editor_mode : public application_mode, private editor_track::observer, pri
// of the modifiers laid
std::size_t nmt_shape_tracks(std::vector const *Only = nullptr);
void nmt_update();
+ // the terrain of the scenery made from the model around the camera within the download area, a chunk at a time while nothing
+ // else is done with the model and the frames are quick: edited chunks wait in memory to be saved, so not the whole area at once
+ void nmt_area_terrain();
void nmt_grow();
void render_nmt_ui();
// where the scenery lies: the map to click on, the place typed; true once it's placed
@@ -483,9 +571,15 @@ class editor_mode : public application_mode, private editor_track::observer, pri
void nmt_restore_terrain(std::vector const &Tracks);
// the terrain of the selected tracks in the panel of the tracks
void render_track_terrain(std::vector const &Tracks);
- // all the tracks of the scenery onto the terrain model, or it under them: step 3 of the terrain model (Terrain_panel), and in
+ // all the tracks of the scenery onto the terrain model, or it under them: step 2 of the terrain model (Terrain_panel), and in
// the panel of the tracks
void render_nmt_all_tracks(bool const Terrain_panel);
+ // what the last putting of the tracks onto the terrain did, and the places it found to be looked at, each to be shown
+ void render_nmt_result();
+ // a line from From to To being put onto the terrain kept to be looked at: the place of it to show and what's wrong there
+ void nmt_note(nmt_state::finding::kind const What, TTrack *From, TTrack *To, double const Length, glm::dvec3 const &Where, std::string Text, double const Size = 0.0);
+ // the place found shown in the 3d view with the track there selected; Profile: the profile of its line opened too
+ void nmt_show(nmt_state::finding const &Finding, bool const Profile);
// the chunks waiting for the terrain model and the tiles of the imagery asked for outlined where they will be, so it's seen
// what's on its way
void draw_nmt_pending() const;
@@ -501,10 +595,45 @@ class editor_mode : public application_mode, private editor_track::observer, pri
glm::dvec3 area_point(glm::dvec2 const &Point) const;
void draw_download_area() const;
void render_download_area_ui(editor_orthophoto::statistics const &Stats);
+ // the download area a square of the side, km, around the camera
+ void area_square(int const Side);
// the chunk of the terrain (x, z) touches the area, or there's none
bool in_download_area(glm::dvec2 const &Low, glm::dvec2 const &High) const;
// over the 3d view while the terrain panel isn't seen
void render_nmt_banner();
+ // the grade lines fitted, the tracks nearly parallel under 5.1 m apart brought onto one, a track going away from them fading back onto its own
+ void nmt_share_grades();
+ void grade_lines_load();
+ void grade_lines_store();
+ bool on_route_grade_line(TTrack const &Track);
+ std::vector const &grade_line_beside();
+ std::size_t grade_line_follow(std::vector const &Before);
+ void grade_line_take_off(bool const Off);
+ // the grade line the route shares, by most of its paths; -1 when it shares none
+ int route_grade_line();
+ // the plain tracks from switch to switch the track is one of, a switch by itself; Alone: the track only
+ static std::vector grade_line_run(TTrack &Track, bool const Alone);
+ // the run of the track clicked onto the grade line of the route by hand, or off it if it's on it; a route sharing none makes one with it
+ void grade_line_pick(TTrack &Track, bool const Alone);
+ // all the tracks of the grade line, wherever they are, for the view while they're picked
+ std::vector const &grade_line_members(int const Number);
+ void draw_grade_line_pick();
+ // a piece split off a track lies on the grade line the track does
+ void grade_line_split(TTrack const &Original, TTrack const &Created);
+ // a track changed keeps its grade line under the key it has after it; a new one between two tracks of a line, a switch put into one, lies on it
+ void grade_line_captured(TTrack const &Track);
+ void grade_lines_committed(std::vector const &Tracks);
+ void grade_line_renamed(TTrack const &Track, std::string const &Old);
+ void render_profile_grade_line();
+ // the tracks laid since the step of the history hidden in the ground, told over the 3d view with the way to fit the ground to them
+ void nmt_check_buried(std::size_t const From);
+ void render_nmt_buried();
+ // what to do first, in the middle of the view of a scenery with no tracks nor terrain
+ void render_empty_scenery_hint();
+ // the camera outside the download area: no photos there, told at the bottom of the view with the way to the area
+ void render_outside_area_hint();
+ // the 3d camera under the ground, as after the view from above or the terrain model made under it, lifted over it
+ void camera_above_ground();
bool nmt_busy() const;
// the terrain made so far stays, what's waiting is dropped, the grade lines not fitted yet are left
void nmt_stop();
@@ -563,6 +692,10 @@ class editor_mode : public application_mode, private editor_track::observer, pri
bool terrain_cursor(glm::dvec3 &World) const;
// the grass of the terrain: the palette, the kind grown, presets
void render_grass_ui();
+ // the point of the ground under the cursor in this frame, for the points put on the ground (outlines, areas, brushes): along the ray
+ // through the cursor to the terrain; the depth read back (a frame late, and stopped by the models over the ground) only where
+ // there's none. false: nothing under the cursor
+ bool cursor_on_ground(glm::dvec3 &World);
// converts the point spacing of the selected chunks to m_terrain_convert_spacing
void convert_selected_chunks();
// the chunks selected with the spacing tool taken out of the terrain, in one step of the history
@@ -618,12 +751,23 @@ class editor_mode : public application_mode, private editor_track::observer, pri
char filter[64]{};
float size{96.f}; // of the images, pixels
std::string selected;
- std::map thumbnails; // texture shown for the item of the name, 0: none
+ struct thumbnail
+ {
+ int texture{0}; // 0: none
+ int material{0}; // the material the texture is the first of, 0: a texture alone
+ double shown{0.0}; // when it was last asked for, ImGui time
+ };
+ std::map thumbnails; // texture shown for the item of the name
+ bool refresh{false}; // all the images to be let go of and read again
int loads{0}; // textures read in the frame, a few at most so the browser doesn't stall the editor
+ int loadsframe{-1};
} m_textures;
void render_texture_browser();
// texture of the image of the item of the browser, 0 while there's none
std::uint64_t texture_thumbnail(texture_browser::item const &Item);
+ // the textures of the images out of sight for a while taken out of the memory: a picker of thousands of them scrolled
+ // through would keep them all, full size, until the memory ran out
+ void thumbnails_trim();
// takes a material dragged from the texture browser onto the item drawn last. returns: true if one was dropped, its name in Name
static bool material_drop(std::string &Name);
// the same, for a text field
@@ -693,8 +837,6 @@ class editor_mode : public application_mode, private editor_track::observer, pri
char m_water_selected_material[128]{""}; // material of the chosen water, while it's edited
int m_water_material_of{-1}; // the water whose material is in the field above
float m_water_selected_size{0.0f}; // metres its texture repeats at, 0: given by the material
- char m_water_default_material[128]{""}; // of the waters which don't name their own, while it's edited
- bool m_water_default_edited{false};
std::set m_terrain_selection; // chunks chosen with the spacing tool
float m_terrain_convert_spacing{1.0f}; // point spacing the selected chunks are converted to
bool m_terrain_convert_paint{true}; // chunks converted to 0.5 m get paint samples every 0.5 m too
@@ -830,6 +972,28 @@ class editor_mode : public application_mode, private editor_track::observer, pri
} m_area_drawing;
std::vector m_nmt_prefetched; // the download area the terrain model was given
bool m_area_paused{false}; // the download of the area held by the button; out of the editor it's held anyway
+ // the terrain made around the camera within the area: the chunks there, nearest first, the next one looked at, when the next one
+ // may be made, those made (or left: the model has no data there, or the chunk is outside the region) since the scenery opened
+ struct area_terrain
+ {
+ std::vector keys;
+ std::size_t next{0};
+ heightmap::chunk_key centre{0, 0};
+ bool listed{false};
+ double resume{0.0};
+ std::size_t made{0};
+ std::size_t square_made{0}; // of them, in the square around the camera now
+ bool refit{false}; // chunks made since the photos were last laid onto the ground
+ double waiting{-1.0}; // since when the next chunk waits for its model; -1: it doesn't
+ std::string held{"-"}; // what held it last, as logged; empty: nothing
+ double took{0.0}; // s the chunks of the square around the camera took, all and the longest
+ double took_most{0.0};
+ std::set empty;
+ std::optional run_only; // the selftest turned it on or off for its run, the setting left as it is
+ } m_area_terrain;
+ int m_area_square{0}; // km, the side of the square around the camera waiting for its yes in place of the area there is
+ bool m_outside_area_closed{false}; // the note of the camera outside the area closed; open again once it's back inside
+ int m_empty_hint_frame{-10}; // the frame the panel of the empty scenery was last drawn in
glm::dvec2 m_orthophoto_origin_edit{0.0}; // origin being typed in (northing, easting); applied when editing ends
// hierarchy management
@@ -1212,6 +1376,11 @@ class editor_mode : public application_mode, private editor_track::observer, pri
std::optional slip_of(TTrack const &Track) const;
// the two tracks of the slip through it from end to end, as they cross where it's taken out
static std::array slip_throughs(slip_set const &Slip);
+ // the slip taken out with its record, nothing of it put in the history yet; with Throughs its two tracks laid crossing in its
+ // place, given back
+ std::vector slip_taken_out(slip_set const &Slip, bool const Throughs);
+ // the record of the crossing of two plain tracks the track is one of
+ std::optional crossing_record(TTrack const &Track) const;
// the paths of the set in the order editor_track::place_switch gives them
static std::vector double_paths(double_switch const &Set);
// the switch of the template, or the two switches of a double one with the plain track between them, committed and recorded
@@ -1380,6 +1549,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri
struct switch_tool
{
std::vector keep_names; // the names the switches laid next take, before the ones of the tool
+ std::string keep_slip; // the name the slip or the crossing laid next takes, of the one it's laid in place of
bool curved{false};
// a switch placed where there's no track: started on the ground, or at the free end it goes on from in its direction; the direction
// of its main track taken from the drag once it's long enough, then the drag sideways gives the side of the diverging one
@@ -1444,13 +1614,18 @@ class editor_mode : public application_mode, private editor_track::observer, pri
double slide_typed{0.0};
int connection{-1};
int connection_kind{0}; // the kind of connection chosen last, taken again when the connections are chosen
- bool rail_only{true}; // the templates listed only for the rail of the selected track, where its rail profile tells it
+ std::string rail_pick{"60E1"}; // the rail whose templates are listed first where the track doesn't tell its rail
int connection_second{-1};
double connection_radius{0.0};
double connection_gap{6.0};
bool connection_together{false};
char connection_spacings[64]{"4.75;4.75;5.0"};
double connection_stub{25.0};
+ // the connection a switch dragged makes, as where it's let go tells it, in connection then: let go on the other track a
+ // crossover, across the tracks between them a ladder; by a crossover there already turned the other way a double crossover
+ // with it, over it a scissors one
+ bool recognised{false};
+ TTrack *partner{nullptr}; // a switch of the crossover there already
};
switch_tool m_switch;
// what the switch tool places: a switch into a straight or a curve, a slip switch or a crossing at a crossing of two
@@ -1466,12 +1641,45 @@ class editor_mode : public application_mode, private editor_track::observer, pri
void choose_switch_kind(switch_kind const Kind);
bool switch_kind_offered(switch_kind const Kind) const;
bool plan_connection(connection::request &Request, connection::result &Result) const;
+ // what the drag of the switch being placed makes, from where the cursor is: sets connection and partner of the tool
+ void recognise_connection();
+ // the double or the scissors crossover of the partner and the crossover dragged, on the lines of their tracks
+ bool plan_partner_connection(connection::request &Request, connection::result &Result) const;
+ void insert_partner_connection();
+ // the switches and the inserts of the connection planned laid, one step of the history. false if they don't fit
+ bool lay_planned_connection(connection::request const &Request, connection::result const &Plan, TTrack *Style);
void insert_connection();
void render_connection_options();
// the name of a kind of connection of tracks, translated
static char const *connection_name(int const Kind);
// the name of a switch template for the lists: where it comes from and its name without the lengths
static std::string switch_template_label(editor_track::switch_template const &Template);
+ // the name of a switch template for the user: translated, with the speed on its diverging track
+ static std::string template_name(editor_track::switch_template const &Template);
+ // the template of the catalogue a record of the switches was laid of, -1 if none: Lengths compares a and b too, which the
+ // record of a connection keeps for its spacing; Movable: the nose of the frog, either when not given
+ int matching_template(switch_store::record const &Record, bool const Lengths, std::optional const Movable = std::nullopt) const;
+ // the template the switch was laid of, -1 if none: a switch of the scenery of its own shape, say
+ int switch_template_index(TTrack const &Switch) const;
+ // why the switch can't take another template here, empty when it can
+ std::string template_change_blocked(TTrack const &Switch) const;
+ // the template of the catalogue a slip or a crossing was laid of, of the rail before the others; -1 if none
+ int slip_template_index(switch_store::record const &Record, std::string const &Rail) const;
+ // the switch of the template of the index in place: its start and its side kept, the tracks it joins following; a switch of a
+ // crossover takes the crossover with it, laid again, a slip or a crossing is laid again where its tracks cross. One step of the
+ // history; the status says how it went
+ bool change_switch_template(TTrack &Switch, int const Index);
+ bool change_slip_template(TTrack &Part, int const Index);
+ // the switch, or the double switch it's a part of, given the shape in place, straight or bent into the curve it lies in; Flip:
+ // the diverging track to the other side. Notes: for the user
+ bool apply_switch_template(TTrack &Switch, editor_track::switch_template const &Shape, bool const Flip, std::string &Notes);
+ // the template to choose: the speeds on the diverging track as chips, the templates of the rail by their skos, all the others
+ // folded under. Fits: those of the kind wanted; Rail: of the track, empty when it doesn't tell; Popup: inside a combo, with no
+ // windows of its own. Gives the index picked, -1 while none is
+ int render_template_picker(char const *Id, std::function const &Fits, std::string const &Rail, int const Chosen, bool const Popup);
+ // the template of the selected switch, slip or crossing, changed with a pick: in a combo for the inspector, else in full; nothing
+ // for another track
+ void render_switch_template(TTrack &Track, bool const Combo);
std::string connection_readout(connection::result const &Plan) const;
editor_track::straight straight_near(glm::dvec3 const &Point, std::vector const &Exclude, double const Reach) const;
editor_track::straight straight_through(glm::dvec3 const &Point, glm::dvec2 const &Direction) const;
@@ -1513,6 +1721,9 @@ class editor_mode : public application_mode, private editor_track::observer, pri
// the paths of the switch moved along the curve by the distance, shaped as the curve is there
std::vector bent_switch_paths(TTrack const &Track, std::vector const &Frame, double const Station, double const Distance) const;
bool slide_bent_switch(TTrack &Track, double const Distance);
+ // the switch bent into a curve given the paths, along the curve of the bent_switch_frame: the tracks next to it laid along it up to
+ // its new ends, one taken up whole going, the curve past the diverging track following. Notes: for the user
+ bool lay_bent_switch(TTrack &Track, std::vector const &Frame, std::array const &Sides, std::vector const &Paths, std::string &Notes);
void switch_slide_start(TTrack &Track);
void switch_slide_update();
void switch_slide_finish();
@@ -1525,7 +1736,6 @@ class editor_mode : public application_mode, private editor_track::observer, pri
void advance_switch_name();
void join_last_steps();
bool render_switch_drive_choice();
- int m_turnout_template{0};
struct turntable_template
{
std::string file;
@@ -1654,6 +1864,31 @@ class editor_mode : public application_mode, private editor_track::observer, pri
std::vector preview;
std::string preview_error;
double preview_length{0.0};
+ // the line worked out whole last, all its fits done: shown while the one of the cursor now still waits for them on the thread,
+ // so that the curves don't jump from one fit to the next as each comes
+ struct worked_out
+ {
+ std::vector preview;
+ std::string error;
+ double length{0.0};
+ lay_line_plan plan;
+ std::optional eased;
+ alignment::join_result join;
+ std::vector points; // the ones clicked it was worked out for
+ };
+ std::optional shown;
+ // the cursor the line is being worked out for, kept till all its fits are done: what it was worked out from
+ struct settling_cursor
+ {
+ glm::dvec3 mouse{0.0};
+ editor_track::snap_target snap;
+ std::vector points;
+ std::vector modes;
+ lay_mode mode{lay_mode::straights};
+ int edits{0};
+ };
+ std::optional settling;
+ bool whole{true}; // false: each fit shown as it comes, as before, for a selftest to compare
double radius{500.0};
double piece_length{100.0};
bool copy_selected{false};
@@ -1706,12 +1941,16 @@ class editor_mode : public application_mode, private editor_track::observer, pri
mutable std::vector, alignment::trace_stretch>> m_stretch_cache;
// the stretch the cursor moves along is fitted on a thread, the frames drawn meanwhile with the fit done last
mutable alignment::stretch_fitter m_stretch_fitter;
+ // a fit the line asked the thread for isn't done yet: the line is one of the fits meanwhile
+ mutable bool m_fits_waiting{false};
+ // how much more the curve at the cursor was turned last to reach it, the first one tried for the next line
+ mutable double m_turned_last{0.0};
void render_switch_ui();
void render_switch_timbers();
void render_rail_profile_hint(TTrack &Track);
bool start_switch_placement();
void finish_switch_placement();
- // a switch with no track there: where a press on the ground starts it, at the free end of a track within reach or right there
+ // a switch with no track under it: a press on the ground starts it at the free end of a track within reach, none with no free end near
editor_track::snap_target free_switch_end(glm::dvec3 const &Ground) const;
bool free_switch_offered() const;
void start_free_switch(glm::dvec3 const &Ground);
@@ -1741,6 +1980,23 @@ class editor_mode : public application_mode, private editor_track::observer, pri
void insert_free_switch();
std::vector switch_preview() const;
std::vector switch_preview_now() const;
+ // where a switch can't go, or doesn't go where it's dragged: what's in the way blinking in the view, each point told what's there,
+ // why by the cursor; while it's dragged, and a while after it's refused
+ struct switch_problem
+ {
+ std::string text;
+ std::vector paths;
+ std::vector> marks;
+ };
+ // what's at the end of the straight: a curve beginning, a switch, the track ending
+ std::string straight_end_note(editor_track::straight const &Line, bool const Far) const;
+ std::optional switch_drag_problem() const;
+ std::optional straight_switch_problem(editor_track::straight const &Line, double const Length, double const Along, int const Direction) const;
+ void flash_switch_problem(switch_problem Problem);
+ void flash_switch_problem(std::string const &Text, std::vector Paths, std::vector> Marks = {});
+ void draw_switch_problem(switch_problem const &Problem) const;
+ switch_problem m_switch_flash;
+ double m_switch_flash_until{-1.0};
// a preview worked out once a frame for the drawing and the readouts which all show it: the frame and the state of the tool it
// was worked out for
template struct frame_memo
@@ -1797,7 +2053,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri
// the single crossover the switch is a part of, along a curve or straights
std::optional crossover_of(TTrack const &Switch) const;
bool take_out_crossover(curved_crossover const &Crossover, std::vector> &States, std::vector &Created, std::vector &Removed, TTrack *&First, TTrack *&Second);
- bool slide_curved_connection(TTrack &Switch, double const Distance);
+ bool slide_curved_connection(TTrack &Switch, double const Distance, int const Shape = -1);
// the template a crossover was laid of, -1 if it's not among the templates
int crossover_template(switch_store::record const &Record);
// a crossover laid again from the press on one track to the release by the other, as by the mouse. false if it doesn't fit
@@ -1814,8 +2070,9 @@ class editor_mode : public application_mode, private editor_track::observer, pri
double along{0.0};
int direction{1};
int side{1};
- segment_data insert;
+ std::vector inserts; // a straight one, or an aligning curve between straights onto a track not parallel
std::vector paths;
+ connection::result connection; // as it's kept with the two switches
};
bool plan_crossover(crossover_plan &Plan) const;
struct switch_link
@@ -1974,8 +2231,10 @@ class editor_mode : public application_mode, private editor_track::observer, pri
editor_icons::icon picture;
int family; // 0 builds the track, 1 equips it, 2 checks it
};
- static std::array const &track_modes();
+ static std::array const &track_modes();
bool track_plan_tab() const { return m_track_tab == track_tab::straights || m_track_tab == track_tab::route; }
+ // a tool of the station: they share its schematic
+ bool srk_tab() const { return m_track_tab == track_tab::station || m_track_tab == track_tab::station_signals || m_track_tab == track_tab::line_block; }
track_tab plan_tab_for(TTrack const *Track) const;
// the objects along the track: a tab for each tool
int m_lineside_tab{0};
@@ -1994,7 +2253,18 @@ class editor_mode : public application_mode, private editor_track::observer, pri
bool stretched{true};
double quick_radius{300.0};
double quick_ratio{9.0};
- double quick_straight{0.0};
+ double quick_a{0.0};
+ double quick_b{0.0};
+ int fit_kind{3}; // of switch_design::tangent_fit
+ double quick_first{0.0}; // the radius of the first arc of an arc, a straight and an arc, 0: the R
+ bool picking{false}; // the switch clicked off the view, the orthophoto under it
+ std::vector clicks;
+ bool on_view{true}; // the template shown in the view where its first points were clicked
+ switch_design::design measured; // what the points clicked so far make
+ bool measured_ready{false};
+ std::string measured_text;
+ int pointed{-1}; // the value under the mouse, its dimension shown on the drawing
+ int pointed_test{-1};
double blade_length{5.0};
double blade_gap{0.15};
std::string status;
@@ -2004,6 +2274,14 @@ class editor_mode : public application_mode, private editor_track::observer, pri
// the list of the switch tool built again with the own templates, keeping the armed one or arming the one whose label starts with Arm
void switch_templates_refresh(std::string const &Arm = {});
void render_switch_designer();
+ void switch_designer_click(glm::dvec3 const &Point);
+ void switch_designer_measure();
+ void switch_designer_finish();
+ void draw_switch_designer_clicks() const;
+ void draw_cursor_ring(glm::dvec3 const &Point) const;
+ static std::string grade_line_key(TTrack const &Track);
+ static std::string grade_line_key(std::string const &Name, TTrack const &Track);
+ static void move_path_heights(segment_data &Path, double const First, double const Second, std::function const &After = {});
bool m_track_window_open{false};
// the inspector is pinned to the right edge of the screen, the profile strip to the bottom one, both resized from the inner edge
void render_track_inspector();
@@ -2051,7 +2329,6 @@ class editor_mode : public application_mode, private editor_track::observer, pri
// a scenery with no tracks yet: in the middle of the view, how the first one is laid
void draw_empty_scenery_hint();
// path under the cursor, outlined before a click so it's known which one the click takes
- using track_hover = ::track_hover;
track_hover m_hover;
track_hover track_under_cursor(TTrack const *Only = nullptr, float const Pixels = 0.0f) const;
track_hover split_spot() const;
@@ -2067,7 +2344,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri
void draw_track_hover() const;
struct track_intent
{
- enum class kind { none, gizmo, select, point, box, straight_set, straight_break, detour, straight_tool, straight_handle, route_vertex, route_grip, switch_at, switch_free, lay, lay_end, sweep, turntable_place, turntable_exit, turntable_fit, spread, extend_end, signal_place, signal_move, switch_slide, pick_style, fouling, measure, route_trace, kilometrage, srk_boundary, catenary };
+ enum class kind { none, gizmo, select, point, box, straight_set, straight_break, detour, straight_tool, straight_handle, route_vertex, route_grip, switch_at, switch_free, lay, lay_end, sweep, turntable_place, turntable_exit, turntable_fit, spread, extend_end, signal_place, signal_move, signal_read, switch_slide, pick_style, grade_line_pick, fouling, measure, route_trace, kilometrage, srk_boundary, srk_joint, catenary };
kind what{kind::none};
TTrack *track{nullptr};
int path{0};
@@ -2244,14 +2521,43 @@ class editor_mode : public application_mode, private editor_track::observer, pri
std::size_t set_switch_timbers(std::string const &Model);
int track_property_index(std::string const &Key) const;
std::size_t track_property_apply(int const Property, std::vector const &Tracks, std::string const &Text);
+ void track_field_finish();
void track_field_settle();
void track_textures_scan();
+ // a texture in use, offered first in the picker
+ struct texture_use
+ {
+ material_handle material{null_handle}; // null: its image is read by the name
+ std::string name;
+ int count{0}; // shown on its tile, 0: nothing
+ std::string note; // what's said of it above the tiles
+ };
+ // what the picker of a texture offers besides every texture of the folder
+ struct texture_offer
+ {
+ char const *title; // the heading of the ones in use
+ std::function()> used; // gathered when the picker opens
+ char const *none; // the entry for no texture, nullptr: there's none
+ char const *none_name; // the name that entry gives
+ };
// every texture and material under the folder of the textures, read on the first use of the picker
- void track_textures_index();
- // the picker of a texture of the rails (Kind 0) or of the trackbed (1), in an open combo. returns: true when one is chosen, its name in Chosen, "none" for no texture
+ void textures_index();
+ // the picker of a texture, in an open combo. returns: true when one is chosen, its name in Chosen
+ bool texture_picker(texture_offer const &Offer, std::string const &Current, bool const Mixed, std::string &Chosen);
+ // the same, of a texture of the rails (Kind 0) or of the trackbed (1)
bool track_texture_picker(int const Kind, std::string const &Current, bool const Mixed, std::string &Chosen);
- // image of the texture of the name for the picker, 0 while there's none
+ // image of the texture of the name, 0 while there's none
+ std::uint64_t texture_image(std::vector