From 65b45839fdd5ebd3f1ee3b730b9e98331df89e1f Mon Sep 17 00:00:00 2001 From: pol102 Date: Fri, 27 Nov 2026 23:20:30 +0100 Subject: [PATCH 1/7] Editor: track names outside of ASCII listed, not renamed; every name the editor gives is plain ASCII (#376) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(editor): track names with characters outside of ASCII changed to ASCII when a scenery is opened for editing, with a 20 s warning in the middle of the screen Tracks, and events named after a track (:event0), are still found by their old names, so events, trainsets and memory cells keep working. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * chore(editor): the brush and the ASCII track names cleaned up for Sonar (init-statements, std::numbers::pi, ranges, the dab of the stroke and the settings of many models in functions of their own) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * chore(editor): the rest of the Sonar notes of the PRs (bytes as numbers, std::format, no copy of the old track name, no shadowed names, try_emplace, deduced template arguments) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DDcMn1Q7wdYkbxDUWscNHZ * feat(editor): the track names outside of ASCII listed, not renamed; the names the editor gives are ASCII only Reworked after the reviews of maj00r and jerrrrycho and the proposal on the PR: renaming the tracks of existing sceneries as they're opened, and then chasing every reference to the old names, broke references it couldn't reach (memory cells in files the editor doesn't write, folded names colliding, the parameters of includes naming events and cells, names outside of Latin folding to underscores), and its fallback ran in the game too. So: - Nothing is renamed when a scenery is opened for editing. The tracks whose names have characters outside of ASCII are listed in the log, and the status line says how many there are and that they work as they are. - Tools -> "Track names outside of ASCII..." opens the list: each name as it reads, its ASCII form, whether that form is taken (by another path, or another name giving the same), whether the name comes from a parameter of an include, and whether its file is one the editor writes. It changes nothing; a track is renamed, if at all, by hand in its properties, where the cells, includes and events it touches are shown. - editor_track::name_valid() refuses a name with characters outside of ASCII, so every name the editor gives (the track properties, the switches, the stations) is plain ASCII. - The game is as on master: no folded lookups of paths or events (path_table::find, FindEventAscii and the map behind it are gone), so a reference to a missing name is reported as before and never binds to another track. The big warning in the middle of the screen is gone with the renaming it announced. ascii_name (plain, fold, readable) and its tests stay, for the list. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QRgQ1K1Qu7TCsa74zsNURd * fix(editor): the switch tool takes no name outside of ASCII The Name field of the switch tool went straight to switch_name_for_new(), so a typed name such as łąka1 became the name of the new switch and of its drive events, outside the check of editor_track::name_valid(). A letter outside of ASCII is now refused as it's typed, with the reason name_valid() gives. Co-Authored-By: Claude Opus 5.5 * fix(editor): the switch, turntable and SRK station code fields drop letters outside of ASCII as they're typed; the include-named tracks said where they're renamed A character filter (ImGuiInputTextFlags_CallbackCharFilter) keeps the refused letter out of the field, so it no longer shows while the switch name is typed. The turntable name and the SRK station code go into track names too and get the same filter. The window of the track names outside of ASCII says that a track named by an include parameter is renamed through that parameter, not in the track properties. * Revert "fix(physicslog): no road-vehicle logs, formatting on the writer, a slow disk and the closing kept short (#408)" This reverts commit d6c35935209a7e5b67c5a5030f660704ee91ca6f. * fix(editor): a letter outside ASCII refused in the turntable name goes to the status line as an error, as in the switch tool The nit of the review of #376 (jerrrrycho, 21.11): the turntable tool set its own status only, while the switch tool reports the same refusal through refused(), which also puts it in the status line of the editor as an error. The text is the same. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QRgQ1JTXWSz4YufC1QZtrY --------- Co-authored-by: Claude Co-authored-by: jerrrrycho --- CMakeLists.txt | 2 + application/editormode.cpp | 13 +- application/editormode.h | 14 ++ application/editormodeshared.h | 12 ++ application/editormodesrk.cpp | 13 +- application/editormodeswitchtool.cpp | 6 +- application/editormodetracknames.cpp | 122 ++++++++++++++++ application/editormodeturntable.cpp | 6 +- editor/editorTrack.cpp | 7 + lang/editor_pl.po | 36 +++++ tests/unit/CMakeLists.txt | 1 + tests/unit/test_asciiname.cpp | 40 ++++++ utilities/asciiname.cpp | 203 +++++++++++++++++++++++++++ utilities/asciiname.h | 29 ++++ 14 files changed, 498 insertions(+), 6 deletions(-) create mode 100644 application/editormodetracknames.cpp create mode 100644 tests/unit/test_asciiname.cpp create mode 100644 utilities/asciiname.cpp create mode 100644 utilities/asciiname.h diff --git a/CMakeLists.txt b/CMakeLists.txt index f5f18344f..698f26823 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -127,6 +127,7 @@ list(APPEND CMAKE_MODULE_PATH "${VCPKG_INSTALLED_PATH}/share") set(SOURCES "model/Texture.cpp" "utilities/Timer.cpp" +"utilities/asciiname.cpp" "utilities/workerpool.cpp" "utilities/memorystats.cpp" "world/Track.cpp" @@ -306,6 +307,7 @@ set(SOURCES "application/editormodelineside.cpp" "application/editormodevehicle.cpp" "application/editormodeselection.cpp" +"application/editormodetracknames.cpp" "application/editormodeviewport.cpp" "application/editormodefields.cpp" "application/editormodeterrainchunks.cpp" diff --git a/application/editormode.cpp b/application/editormode.cpp index 2cb34401c..132c61dfd 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -584,7 +584,16 @@ editor_mode::editor_mode() { ui()->set_open_scenery([this]() { m_openscenery_asked = true; }); ui()->set_memcell_focus([this](scene::basic_node *Node) { start_focus(Node); }); ui()->set_edit_menu([this]() { render_edit_menu(); }); - ui()->set_tools_menu([this]() { render_track_presets_menu(); }); + ui()->set_tools_menu([this]() { + render_track_presets_menu(); + if (ImGui::MenuItem(STR_C("Track names outside of ASCII..."), nullptr, m_track_names_open)) + { + check_track_names(false); + m_track_names_open = true; + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The tracks whose names have Polish letters or other characters outside of ASCII, and what an ASCII name would collide with; nothing is changed")); + }); ui()->set_menu_options([this]() { render_object_menu(); render_view_menu(); @@ -1715,6 +1724,7 @@ bool editor_mode::update() m_gauge.update(); m_gauge.render_windows(); m_minimap.render_windows(); + render_track_names_window(); // roads: trajectories of the lanes, and the tools of the road window update_road_tool(); @@ -7609,6 +7619,7 @@ void editor_mode::enter() if (Global.editor_session && false == m_opened_at_track) { m_opened_at_track = true; + check_track_names(true); auto const saved{scene::Layers.empty() ? std::vector{} : scene::Layers.marked(scene::layer_handle{1}, "//$c")}; if (false == saved.empty()) { diff --git a/application/editormode.h b/application/editormode.h index 7277872b4..ad09e9d5e 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -948,6 +948,20 @@ class editor_mode : public application_mode, private editor_track::observer, pri bool restart_editor(std::string const &Scenery); bool m_openscenery_asked{false}; bool m_opened_at_track{false}; + // the tracks whose names have letters outside of ASCII, listed once the scenery is opened for editing and in a window of their + // own: nothing is renamed, the names the scenery has go on working as they did; the editor gives no new name outside of ASCII + struct track_name_entry + { + std::string name; // as it reads (UTF-8) + std::string ascii; // the name without the letters outside of ASCII + bool clash{false}; // another path has that name already, or another name gives the same + bool include{false}; // given by a parameter of an include, which names more than the track with it + bool written{true}; // in a file the editor writes + }; + std::vector m_track_names; + bool m_track_names_open{false}; + void check_track_names(bool Report); + void render_track_names_window(); bool m_turntable_included{false}; bool turntable_controls(std::vector &Rootstatements); bool m_nose_included{false}; diff --git a/application/editormodeshared.h b/application/editormodeshared.h index 516aada88..312241a9b 100644 --- a/application/editormodeshared.h +++ b/application/editormodeshared.h @@ -58,6 +58,18 @@ inline void item_tooltip(char const *Text) ImGui::SetTooltip("%s", STR_C(Text)); } +// the callback of a name field with ImGuiInputTextFlags_CallbackCharFilter: the names the editor gives are plain ASCII +// (editor_track::name_valid), so a letter outside of it is dropped as it's typed or pasted and never shows in the field. +// UserData, when given, is a bool set to true once a letter was dropped +inline int ascii_only_filter(ImGuiInputTextCallbackData *Data) +{ + if (Data->EventChar < 0x80) + return 0; + if (Data->UserData != nullptr) + *static_cast(Data->UserData) = true; + return 1; +} + // grid points without a height (or another value) take the one of the nearest point which has it (by steps along the grid) template inline void fill_from_nearest(std::vector &Heights, std::vector &Found, std::size_t const Side) { diff --git a/application/editormodesrk.cpp b/application/editormodesrk.cpp index b31178e04..15ec62ba5 100644 --- a/application/editormodesrk.cpp +++ b/application/editormodesrk.cpp @@ -1443,19 +1443,26 @@ void srk_tool::render_station() auto const &layout{*m_layout}; if (begin_fields("##srkstation")) { - auto const text = [&](char const *Label, char const *Id, std::string const &Value, char const *Hint, auto const &Set) { + // Ascii: the value goes into the names the editor gives (editor_track::name_valid), so a letter outside of ASCII is dropped as it's typed + auto const text = [&](char const *Label, char const *Id, std::string const &Value, char const *Hint, auto const &Set, bool const Ascii = false) { field_row(Label); std::array buffer{}; Value.copy(buffer.data(), buffer.size() - 1); - if (ImGui::InputTextWithHint(Id, Hint, buffer.data(), buffer.size())) + bool dropped{false}; + if (ImGui::InputTextWithHint(Id, Hint, buffer.data(), buffer.size(), Ascii ? ImGuiInputTextFlags_CallbackCharFilter : ImGuiInputTextFlags_None, ascii_only_filter, &dropped)) { Set(std::string{buffer.data()}); m_changed = true; } + if (dropped) + { + begin_status(); + refuse(STR("The name can hold ASCII only: no Polish letters or other characters outside of it")); + } }; auto const *entry{m_record >= 0 ? &m_records[m_record] : nullptr}; text("Name", "##srkname", entry != nullptr ? entry->name : std::string{}, example("Biała Podlaska").c_str(), [&](std::string const &Value) { record_of_open().name = Value; }); - text("Code", "##srkcode", entry != nullptr ? entry->code : std::string{}, example("BPd").c_str(), [&](std::string const &Value) { record_of_open().code = word_of(Value) == "-" ? std::string{} : word_of(Value); }); + text("Code", "##srkcode", entry != nullptr ? entry->code : std::string{}, example("BPd").c_str(), [&](std::string const &Value) { record_of_open().code = word_of(Value) == "-" ? std::string{} : word_of(Value); }, true); item_tooltip("The abbreviation of the station: the names of its switches, track circuits and signals begin with it"); auto const line_hint{line_of_open()}; text("Line", "##srkline", entry != nullptr ? entry->line : std::string{}, line_hint.empty() ? example("2").c_str() : line_hint.c_str(), [&](std::string const &Value) { record_of_open().line = word_of(Value) == "-" ? std::string{} : word_of(Value); }); diff --git a/application/editormodeswitchtool.cpp b/application/editormodeswitchtool.cpp index 878e18aa3..f13b7429f 100644 --- a/application/editormodeswitchtool.cpp +++ b/application/editormodeswitchtool.cpp @@ -255,7 +255,11 @@ void editor_mode::render_switch_ui() if (begin_fields("##switchnamefields", 0.3f)) { field_row("Name##switchname"); - ImGui::InputTextWithHint("##switchname", switch_name_for_new().c_str(), tool.name, sizeof(tool.name)); + // the names the editor gives are plain ASCII (editor_track::name_valid): a letter outside of it is dropped as it's typed + bool dropped{false}; + ImGui::InputTextWithHint("##switchname", switch_name_for_new().c_str(), tool.name, sizeof(tool.name), ImGuiInputTextFlags_CallbackCharFilter, ascii_only_filter, &dropped); + if (dropped) + tool.status = refused(STR("The name can hold ASCII only: no Polish letters or other characters outside of it")); item_tooltip("Name of the next switch, its drive events are named after it; empty: the next free z1, z2...; a number at the end goes up with each switch"); ImGui::EndTable(); } diff --git a/application/editormodetracknames.cpp b/application/editormodetracknames.cpp new file mode 100644 index 000000000..19eed5770 --- /dev/null +++ b/application/editormodetracknames.cpp @@ -0,0 +1,122 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +// the tracks whose names have letters outside of ASCII: listed, nothing renamed. The names the sceneries have go on working as they +// always did, in the editor and in the game; the editor gives no new name outside of ASCII (editor_track::name_valid) + +#include "stdafx.h" + +#include "application/editormode.h" +#include "application/editoruilayer.h" +#include "editor/editorFormat.hpp" +#include "editor/editorTrack.hpp" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/asciiname.h" +#include "utilities/translation.h" + +#include +#include +#include +#include +#include + +namespace +{ + +// the tracks listed: the lanes take their names from their road, the removed ones are gone +bool listed(TTrack const *Track) +{ + return Track != nullptr && false == Track->m_editorremoved && (Track->iCategoryFlag & 0x80) == 0 && Track->m_road == nullptr && false == Track->name().empty() && + false == ascii_name::plain(Track->name()); +} + +char const *yes_no(bool const Value) +{ + return Value ? STR_C("yes") : STR_C("no"); +} + +} // namespace + +void editor_mode::check_track_names(bool const Report) +{ + m_track_names.clear(); + std::vector found; + std::map folded; // how many of the names listed give each ASCII name + for (auto const *track : simulation::Paths.sequence()) + { + if (false == listed(track)) + continue; + found.push_back(track); + ++folded[ascii_name::fold(track->name())]; + } + for (auto const *track : found) + { + track_name_entry entry; + entry.name = ascii_name::readable(track->name()); + entry.ascii = ascii_name::fold(track->name()); + // another path named so already, or another name listed giving the same + auto const *other{simulation::Paths.find(entry.ascii)}; + entry.clash = (other != nullptr && other != track && false == other->m_editorremoved) || folded[entry.ascii] > 1; + entry.include = track->from_template() && editor_track::uses_of_name(*track).includes > 0; + entry.written = track->from_template() ? entry.include : scene::Layers.editable(track); + m_track_names.push_back(std::move(entry)); + } + if (false == Report || m_track_names.empty()) + return; + for (auto const &entry : m_track_names) + WriteLog(std::format(R"(Editor: track "{}" has characters outside of ASCII in its name; in ASCII "{}"{})", entry.name, entry.ascii, entry.clash ? ", a name taken already" : "")); + ui()->set_status(format(STR_C("%zu track names have characters outside of ASCII; they work as they are, the list is in Tools"), m_track_names.size())); +} + +void editor_mode::render_track_names_window() +{ + if (false == m_track_names_open) + return; + ImGui::SetNextWindowSize(ImVec2(620.0f * Global.ui_scale, 380.0f * Global.ui_scale), ImGuiCond_FirstUseEver); + if (false == ImGui::Begin((std::string(STR_C("Track names outside of ASCII")) + "###tracknamesascii").c_str(), &m_track_names_open)) + { + ImGui::End(); + return; + } + ImGui::TextWrapped("%s", STR_C("These names work as they are and nothing here changes them. New names given in the editor are ASCII only. To give one of these tracks an ASCII name, rename it in the track properties: the memory cells and the includes which name it go along, the events named after it are listed there. A track named by a parameter of an include (From an include: yes) can't be renamed there: change that parameter in the line of the scenery which puts the include.")); + if (ImGui::SmallButton(STR_C("Check again"))) + check_track_names(false); + ImGui::SameLine(); + ImGui::TextDisabled(STR_C("Tracks: %zu"), m_track_names.size()); + auto constexpr flags{ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY | ImGuiTableFlags_Resizable}; + if (ImGui::BeginTable("##tracknamesascii", 5, flags)) + { + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn(STR_C("Name")); + ImGui::TableSetupColumn(STR_C("In ASCII")); + ImGui::TableSetupColumn(STR_C("Taken")); + ImGui::TableSetupColumn(STR_C("From an include")); + ImGui::TableSetupColumn(STR_C("In a file the editor writes")); + ImGui::TableHeadersRow(); + for (auto const &entry : m_track_names) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(entry.name.c_str()); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(entry.ascii.c_str()); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(yes_no(entry.clash)); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(yes_no(entry.include)); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(yes_no(entry.written)); + } + ImGui::EndTable(); + } + ImGui::End(); +} diff --git a/application/editormodeturntable.cpp b/application/editormodeturntable.cpp index 6052bf5c8..ac5bb98aa 100644 --- a/application/editormodeturntable.cpp +++ b/application/editormodeturntable.cpp @@ -1011,7 +1011,11 @@ void editor_mode::render_turntable_ui() if (begin_fields("##turntablenamefields", 0.3f)) { field_row("Name##turntablename"); - ImGui::InputTextWithHint("##turntablename", turntable_name_for_new().c_str(), tool.name, sizeof(tool.name), ImGuiInputTextFlags_CharsNoBlank); + // the name of the bridge track: plain ASCII as every name the editor gives (editor_track::name_valid) + bool dropped{false}; + ImGui::InputTextWithHint("##turntablename", turntable_name_for_new().c_str(), tool.name, sizeof(tool.name), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CallbackCharFilter, ascii_only_filter, &dropped); + if (dropped) + tool.status = refused(STR("The name can hold ASCII only: no Polish letters or other characters outside of it")); ImGui::EndTable(); } gesture_rows({{"Drag", "from where the centre goes, turning the bridge"}, {"LMB on a free end", "the turntable lines up with it, at its end"}, {"Shift+LMB", "no lining up"}}); diff --git a/editor/editorTrack.cpp b/editor/editorTrack.cpp index 2504e7c5d..e380cd440 100644 --- a/editor/editorTrack.cpp +++ b/editor/editorTrack.cpp @@ -26,6 +26,7 @@ http: #include "utilities/utilities.h" #include "utilities/parser.h" #include "utilities/Logs.h" +#include "utilities/asciiname.h" #include #include @@ -483,6 +484,12 @@ bool editor_track::name_valid(TTrack const &Track, std::string &Name, std::strin Reason = "The name can't hold blanks, quotes, semicolons or //"; return false; } + // the names the editor gives are plain ASCII: the code page of a scenery file decides what other letters turn into + if (false == ascii_name::plain(Name)) + { + Reason = "The name can hold ASCII only: no Polish letters or other characters outside of it"; + return false; + } auto *owner{simulation::Paths.find(Name)}; if (owner != nullptr && owner != &Track && false == owner->m_editorremoved) { diff --git a/lang/editor_pl.po b/lang/editor_pl.po index f1260bb5b..4e845d709 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -14313,6 +14313,42 @@ msgstr "Kursor rysowany w obrazie (stream)" msgid "The pointer drawn by the editor into the frame instead of the one of the system: seen by those watching a stream\nor a recording of the window (Discord, OBS, the capture of the system), which leave the system pointer out" msgstr "Wskaźnik rysowany przez edytor w klatce zamiast systemowego: widać go w streamie\ni w nagraniu okna (Discord, OBS, przechwytywanie systemowe), które pomijają wskaźnik systemu" +msgid "Track names outside of ASCII..." +msgstr "Nazwy torów spoza ASCII..." + +msgid "The tracks whose names have Polish letters or other characters outside of ASCII, and what an ASCII name would collide with; nothing is changed" +msgstr "Tory, których nazwy mają polskie litery lub inne znaki spoza ASCII, i z czym zderzyłaby się nazwa w ASCII; nic nie jest zmieniane" + +msgid "%zu track names have characters outside of ASCII; they work as they are, the list is in Tools" +msgstr "%zu nazw torów ma znaki spoza ASCII; działają tak jak są, lista jest w menu Narzędzia" + +msgid "Track names outside of ASCII" +msgstr "Nazwy torów spoza ASCII" + +msgid "These names work as they are and nothing here changes them. New names given in the editor are ASCII only. To give one of these tracks an ASCII name, rename it in the track properties: the memory cells and the includes which name it go along, the events named after it are listed there. A track named by a parameter of an include (From an include: yes) can't be renamed there: change that parameter in the line of the scenery which puts the include." +msgstr "Te nazwy działają tak jak są i nic tutaj ich nie zmienia. Nowe nazwy nadawane w edytorze mogą mieć tylko znaki ASCII. Żeby dać któremuś z tych torów nazwę w ASCII, zmień ją we właściwościach toru: komórki pamięci i include'y, które go nazywają, zmienią się razem z nią, a eventy nazwane od niego są tam wypisane. Toru nazwanego parametrem include'a (Z include'a: tak) nie da się tam przemianować: zmień ten parametr w linii scenerii, która wstawia include." + +msgid "Check again" +msgstr "Sprawdź ponownie" + +msgid "Tracks: %zu" +msgstr "Torów: %zu" + +msgid "In ASCII" +msgstr "W ASCII" + +msgid "Taken" +msgstr "Zajęta" + +msgid "From an include" +msgstr "Z include'a" + +msgid "In a file the editor writes" +msgstr "W pliku zapisywanym przez edytor" + +msgid "The name can hold ASCII only: no Polish letters or other characters outside of it" +msgstr "Nazwa może mieć tylko znaki ASCII: bez polskich liter i innych znaków spoza niego" + msgid "Draws the imagery as part of the scene, so tracks, models and terrain in front of it hide it.\nIt is lit like the scene. Fully opaque, mouse placement lands on it as on any surface;\ntranslucent, it doesn't catch the mouse." msgstr "Rysuje zdjęcia jako część sceny, więc tory, modele i teren przed nimi je zasłaniają.\nJest oświetlone jak scena. W pełni kryjące łapie mysz przy wstawianiu jak każda powierzchnia;\nprzezroczyste nie łapie myszy." diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 3de990dec..347e359e6 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -38,6 +38,7 @@ add_executable(${UNIT_TESTS_NAME} "${CMAKE_SOURCE_DIR}/rendering/common/freecameramotion.cpp" # and the http client the editor fetches its aids with "${CMAKE_SOURCE_DIR}/editor/editorHttp.cpp" + "${CMAKE_SOURCE_DIR}/utilities/asciiname.cpp" # and what the switch tool tells of the drives of the switches "${CMAKE_SOURCE_DIR}/editor/editorSwitchDrives.cpp" # the camera, for the order of its rotations (test_camera.cpp) diff --git a/tests/unit/test_asciiname.cpp b/tests/unit/test_asciiname.cpp new file mode 100644 index 000000000..166947350 --- /dev/null +++ b/tests/unit/test_asciiname.cpp @@ -0,0 +1,40 @@ +#include "stdafx.h" + +#include "doctest.h" + +#include "utilities/asciiname.h" + +TEST_CASE("ascii name: plain names stay as they are") +{ + CHECK(ascii_name::plain("tor_01-a")); + CHECK(ascii_name::fold("tor_01-a") == "tor_01-a"); + CHECK(ascii_name::fold("ToR") == "tor"); +} + +TEST_CASE("ascii name: the Polish letters in UTF-8 lose their marks") +{ + auto const name{std::string{"\xC5\x81\xC4\x85\x6B\x61_\xC5\xBC\xC3\xB3\xC5\x82\x74\xC4\x99_\xC5\x9B\xC4\x87\xC5\x84\xC5\xBA"}}; // Łąka_żółtę_śćńź + CHECK_FALSE(ascii_name::plain(name)); + CHECK(ascii_name::fold(name) == "laka_zolte_scnz"); + CHECK(ascii_name::readable(name) == name); +} + +TEST_CASE("ascii name: the Polish letters in Windows-1250 lose their marks") +{ + // ąćęłńóśźż ĄĆĘŁŃÓŚŹŻ + auto const name{std::string{"\xB9\xE6\xEA\xB3\xF1\xF3\x9C\x9F\xBF_\xA5\xC6\xCA\xA3\xD1\xD3\x8C\x8F\xAF"}}; + CHECK(ascii_name::fold(name) == "acelnoszz_acelnoszz"); + CHECK(ascii_name::readable(name) == "\xC4\x85\xC4\x87\xC4\x99\xC5\x82\xC5\x84\xC3\xB3\xC5\x9B\xC5\xBA\xC5\xBC_\xC4\x84\xC4\x86\xC4\x98\xC5\x81\xC5\x83\xC3\x93\xC5\x9A\xC5\xB9\xC5\xBB"); +} + +TEST_CASE("ascii name: other letters with marks, and whatever else isn't ASCII") +{ + CHECK(ascii_name::fold("Stra\xC3\x9F" "e") == "strasse"); // Straße + CHECK(ascii_name::fold("\xC4\x8C" "esk\xC3\xA1") == "ceska"); // Česká + CHECK(ascii_name::fold("\xC3\x86" "r\xC3\xB8") == "aero"); // Ærø + CHECK(ascii_name::fold("tor\xE2\x82\xAC" "1") == "tor_1"); // the euro sign + CHECK(ascii_name::fold("\xD0\xBF\xD1\x83\xD1\x82\xD1\x8C") == "____"); // путь + CHECK(ascii_name::fold("x\x81y") == "x_y"); // a byte the code page doesn't have + for (int byte = 0x80; byte < 0x100; ++byte) + CHECK(ascii_name::plain(ascii_name::fold(std::string(1, static_cast(byte))))); +} diff --git a/utilities/asciiname.cpp b/utilities/asciiname.cpp new file mode 100644 index 000000000..30f5f5cf0 --- /dev/null +++ b/utilities/asciiname.cpp @@ -0,0 +1,203 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "utilities/asciiname.h" + +#include +#include +#include +#include +#include + +namespace +{ + +// the characters of Windows-1250 from 0x80 up; 0 where the code page has none +constexpr std::array cp1250{ + 0x20AC, 0x0000, 0x201A, 0x0000, 0x201E, 0x2026, 0x2020, 0x2021, 0x0000, 0x2030, 0x0160, 0x2039, 0x015A, 0x0164, 0x017D, 0x0179, + 0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x0000, 0x2122, 0x0161, 0x203A, 0x015B, 0x0165, 0x017E, 0x017A, + 0x00A0, 0x02C7, 0x02D8, 0x0141, 0x00A4, 0x0104, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x015E, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x017B, + 0x00B0, 0x00B1, 0x02DB, 0x0142, 0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x0105, 0x015F, 0x00BB, 0x013D, 0x02DD, 0x013E, 0x017C, + 0x0154, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0139, 0x0106, 0x00C7, 0x010C, 0x00C9, 0x0118, 0x00CB, 0x011A, 0x00CD, 0x00CE, 0x010E, + 0x0110, 0x0143, 0x0147, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x00D7, 0x0158, 0x016E, 0x00DA, 0x0170, 0x00DC, 0x00DD, 0x0162, 0x00DF, + 0x0155, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x013A, 0x0107, 0x00E7, 0x010D, 0x00E9, 0x0119, 0x00EB, 0x011B, 0x00ED, 0x00EE, 0x010F, + 0x0111, 0x0144, 0x0148, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x00F7, 0x0159, 0x016F, 0x00FA, 0x0171, 0x00FC, 0x00FD, 0x0163, 0x02D9}; + +// the letters of Latin-1 from U+00C0 up, without their marks +constexpr std::array latin1{ + "a", "a", "a", "a", "a", "a", "ae", "c", "e", "e", "e", "e", "i", "i", "i", "i", + "d", "n", "o", "o", "o", "o", "o", "_", "o", "u", "u", "u", "u", "y", "th", "ss", + "a", "a", "a", "a", "a", "a", "ae", "c", "e", "e", "e", "e", "i", "i", "i", "i", + "d", "n", "o", "o", "o", "o", "o", "_", "o", "u", "u", "u", "u", "y", "th", "y"}; + +// the letters of Latin Extended-A, U+0100 to U+017F, in runs of the same plain letter +struct run +{ + int count; + std::string_view letter; +}; +constexpr std::array extended{{{6, "a"}, {8, "c"}, {4, "d"}, {10, "e"}, {8, "g"}, {4, "h"}, {10, "i"}, {2, "ij"}, {2, "j"}, {3, "k"}, {10, "l"}, + {9, "n"}, {6, "o"}, {2, "oe"}, {6, "r"}, {8, "s"}, {6, "t"}, {12, "u"}, {2, "w"}, {3, "y"}, {6, "z"}, {1, "s"}}}; + +std::string_view plain_letter(char32_t const Code) +{ + if (Code >= 0xC0 && Code < 0x100) + return latin1[Code - 0xC0]; + if (Code >= 0x100 && Code < 0x180) + { + auto left{static_cast(Code - 0x100)}; + for (auto const &letters : extended) + { + if (left < letters.count) + return letters.letter; + left -= letters.count; + } + } + return "_"; +} + +// the byte at the given place, as a number +std::uint32_t byte_at(std::string_view const Text, std::size_t const At) +{ + return static_cast(static_cast(Text[At])); +} + +// the length of the UTF-8 sequence the byte begins, with the bits of the character it holds; 0 for a byte which can't begin one +int sequence_length(std::uint32_t const Lead, char32_t &Code) +{ + if (Lead < 0x80) + { + Code = Lead; + return 1; + } + if (Lead < 0xC2 || Lead >= 0xF5) + return 0; + if (Lead < 0xE0) + { + Code = Lead & 0x1Fu; + return 2; + } + if (Lead < 0xF0) + { + Code = Lead & 0x0Fu; + return 3; + } + Code = Lead & 0x07u; + return 4; +} + +// the character of the UTF-8 sequence at the given place; false if there's no valid one +bool decode_one(std::string_view const Text, std::size_t const At, int const Length, char32_t &Code) +{ + if (At + Length > Text.size()) + return false; + for (int i = 1; i < Length; ++i) + { + auto const next{byte_at(Text, At + i)}; + if ((next & 0xC0u) != 0x80u) + return false; + Code = (Code << 6) | (next & 0x3Fu); + } + // the shortest form only, as UTF-8 has it + return false == ((Length == 3 && Code < 0x800) || (Length == 4 && (Code < 0x10000 || Code > 0x10FFFF))); +} + +// the characters of a valid UTF-8 text; false if it isn't one +bool decode_utf8(std::string_view const Text, std::vector &Codes) +{ + Codes.clear(); + std::size_t at{0}; + while (at < Text.size()) + { + char32_t code{0}; + auto const length{sequence_length(byte_at(Text, at), code)}; + if (length == 0 || false == decode_one(Text, at, length, code)) + return false; + Codes.push_back(code); + at += length; + } + return true; +} + +std::vector characters(std::string_view const Name) +{ + std::vector codes; + if (decode_utf8(Name, codes)) + return codes; + codes.clear(); + for (std::size_t at = 0; at < Name.size(); ++at) + { + auto const byte{byte_at(Name, at)}; + if (byte < 0x80) + codes.push_back(byte); + else + codes.push_back(cp1250[byte - 0x80] != 0 ? cp1250[byte - 0x80] : 0xFFFD); + } + return codes; +} + +void append_utf8(std::string &Output, char32_t const Code) +{ + if (Code < 0x80) + Output += static_cast(Code); + else if (Code < 0x800) + { + Output += static_cast(0xC0 | (Code >> 6)); + Output += static_cast(0x80 | (Code & 0x3F)); + } + else if (Code < 0x10000) + { + Output += static_cast(0xE0 | (Code >> 12)); + Output += static_cast(0x80 | ((Code >> 6) & 0x3F)); + Output += static_cast(0x80 | (Code & 0x3F)); + } + else + { + Output += static_cast(0xF0 | (Code >> 18)); + Output += static_cast(0x80 | ((Code >> 12) & 0x3F)); + Output += static_cast(0x80 | ((Code >> 6) & 0x3F)); + Output += static_cast(0x80 | (Code & 0x3F)); + } +} + +} // namespace + +namespace ascii_name +{ + +bool plain(std::string_view const Name) +{ + return std::ranges::all_of(Name, [](char const Character) { return static_cast(Character) < 0x80; }); +} + +std::string fold(std::string_view const Name) +{ + std::string result; + result.reserve(Name.size()); + for (auto const code : characters(Name)) + { + if (code < 0x80) + result += static_cast(std::tolower(static_cast(code))); + else + result += plain_letter(code); + } + return result; +} + +std::string readable(std::string_view const Name) +{ + std::string result; + result.reserve(Name.size() * 2); + for (auto const code : characters(Name)) + append_utf8(result, code); + return result; +} + +} // namespace ascii_name diff --git a/utilities/asciiname.h b/utilities/asciiname.h new file mode 100644 index 000000000..1e89b5bb7 --- /dev/null +++ b/utilities/asciiname.h @@ -0,0 +1,29 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include + +// names of the scenery written in plain ASCII. +// a name with letters outside of it is read as UTF-8 when it's valid UTF-8, otherwise as Windows-1250, +// the code page of the most of the sceneries +namespace ascii_name +{ + +// true if the name holds nothing but ASCII +bool plain(std::string_view Name); +// the name in ASCII, in lower case as the parser gives the names: the letters with marks lose them (ł -> l, ß -> ss), +// whatever else isn't ASCII becomes '_' +std::string fold(std::string_view Name); +// the name as UTF-8, to be shown or logged: a name which isn't valid UTF-8 is taken for Windows-1250 +std::string readable(std::string_view Name); + +} // namespace ascii_name From 3bd0193d8dd1d94248f7ebbf46a1867a26758d6a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 27 Nov 2026 23:51:10 +0100 Subject: [PATCH 2/7] feat(vehicle): lowpoly driver figure follows the direction in single desk vehicles (GE#535) (#530) In a vehicle with one desk for both directions (401Da, SM31, TEM2) the AI changes the cab to drive the other way, so from outside its lowpoly figure turns round (mechanik2). The player usually stays in the cab and only moves the reverser, so the figure kept facing forward. When the player drives such a vehicle, the figure now follows the selected direction of travel (DirAbsolute): reverser backwards shows mechanik2, forwards mechanik1. With no direction selected it is the figure of the occupied cab, as before. The AI is unchanged. A vehicle counts as single desk when its .mmd has jointcabs:, cab1model: and cab2model: name the same model and driver1sitpos: and driver2sitpos: (or driverNpos: without a sitpos) are the same spot within 1 cm. Two desks in one cab (SM42, SP42: mirrored seats) and vehicles with two cabs don't match, so they are unchanged. No data change is needed. eu07.ini driverfigure.followsdirection (yes by default); "no" keeps the figure of the occupied cab, as before. The decision is in vehicle/driverfigure.h, tested in tests/unit/test_driver_figure.cpp. --- tests/unit/test_driver_figure.cpp | 119 ++++++++++++++++++++++++++++++ utilities/Globals.cpp | 7 ++ utilities/Globals.h | 1 + vehicle/DynObj.cpp | 54 +++++++++++++- vehicle/DynObj.h | 1 + vehicle/driverfigure.h | 70 ++++++++++++++++++ 6 files changed, 249 insertions(+), 3 deletions(-) create mode 100644 tests/unit/test_driver_figure.cpp create mode 100644 vehicle/driverfigure.h diff --git a/tests/unit/test_driver_figure.cpp b/tests/unit/test_driver_figure.cpp new file mode 100644 index 000000000..a9b59599f --- /dev/null +++ b/tests/unit/test_driver_figure.cpp @@ -0,0 +1,119 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/driverfigure.h" + +// the driver figures of the lowpoly interior (eu07/maszyna#535): in a vehicle with one desk for both directions the +// player's figure follows the selected direction of travel, so a player who only moves the reverser is seen facing the +// way the vehicle goes, the way the AI is, which changes the cab instead + +using driver_figure::cab_place; +using driver_figure::shown; +using driver_figure::single_desk; + +namespace { + +// the cabs of 401da_v2/401da.mmd: the same model and the same seat for both directions +cab_place const desk_401da{"interior/401da-207.t3d", glm::vec3{-0.908f, 3.324f, -1.543f}, glm::vec3{-0.908f, 3.324f, -1.543f}}; + +// tem2_v2/tem2a.mmd: the cab 2 has another standing position, but the same seat +cab_place const tem2_cab1{"kabina-tem2a.t3d", glm::vec3{-1.27f, 3.594f, -5.61f}, glm::vec3{-1.235f, 3.203f, -5.114f}}; +cab_place const tem2_cab2{"kabina-tem2a.t3d", glm::vec3{1.27f, 3.594f, -4.72f}, glm::vec3{-1.235f, 3.203f, -5.114f}}; + +// sm42_v1/6d.mmd: one cab with two desks, the seat of the cab 2 is on the other side +cab_place const sm42_cab1{"6d_kabina.t3d", glm::vec3{0.99f, 3.454f, -3.311f}, glm::vec3{-1.15f, 3.58f, -2.83f}}; +cab_place const sm42_cab2{"6d_kabina.t3d", glm::vec3{-0.99f, 3.454f, -3.311f}, glm::vec3{1.15f, 3.58f, -2.83f}}; + +// a vehicle with a cab at each end +cab_place const end_cab1{"kabina_a.t3d", glm::vec3{-0.8f, 2.5f, 7.0f}, glm::vec3{-0.8f, 2.4f, 7.2f}}; +cab_place const end_cab2{"kabina_a.t3d", glm::vec3{0.8f, 2.5f, -7.0f}, glm::vec3{0.8f, 2.4f, -7.2f}}; + +} // namespace + +TEST_CASE("driver figure: joint cabs with one model and one seat are a single desk") { + CHECK(single_desk(true, desk_401da, desk_401da)); + CHECK(single_desk(true, tem2_cab1, tem2_cab2)); +} + +TEST_CASE("driver figure: without jointcabs: the cabs are never a single desk") { + CHECK_FALSE(single_desk(false, desk_401da, desk_401da)); + CHECK_FALSE(single_desk(false, tem2_cab1, tem2_cab2)); +} + +TEST_CASE("driver figure: two desks in one cab, or two cabs, are not a single desk") { + CHECK_FALSE(single_desk(true, sm42_cab1, sm42_cab2)); + CHECK_FALSE(single_desk(true, end_cab1, end_cab2)); +} + +TEST_CASE("driver figure: the cabs with different models are not a single desk") { + auto cab2{desk_401da}; + cab2.model = "interior/401da-207_b.t3d"; + CHECK_FALSE(single_desk(true, desk_401da, cab2)); + cab2.model = "none"; + CHECK_FALSE(single_desk(true, desk_401da, cab2)); + auto nomodel{desk_401da}; + nomodel.model = "none"; + CHECK_FALSE(single_desk(true, nomodel, nomodel)); + nomodel.model.clear(); + CHECK_FALSE(single_desk(true, nomodel, nomodel)); +} + +TEST_CASE("driver figure: the seat is the sitting position, or the position without one") { + cab_place standing{"cab.t3d", glm::vec3{-1.15f, 3.32f, -4.23f}, std::nullopt}; + REQUIRE(standing.seat().has_value()); + CHECK(standing.seat()->x == doctest::Approx(-1.15)); + CHECK(single_desk(true, standing, standing)); + + // the same sitting position decides, whatever the standing ones (sm31_v1/411d.mmd) + cab_place const sm31_cab1{"cab.t3d", glm::vec3{-1.15f, 3.32f, -4.23f}, glm::vec3{-1.13f, 3.21f, -4.77f}}; + cab_place const sm31_cab2{"cab.t3d", glm::vec3{1.15f, 3.32f, -4.23f}, glm::vec3{-1.13f, 3.21f, -4.77f}}; + CHECK(single_desk(true, sm31_cab1, sm31_cab2)); + + // the cab 1 sits on the standing spot of the cab 2, which has its own seat elsewhere + cab_place const cab2{"cab.t3d", glm::vec3{-1.15f, 3.32f, -4.23f}, glm::vec3{1.15f, 3.21f, -4.77f}}; + CHECK_FALSE(single_desk(true, standing, cab2)); +} + +TEST_CASE("driver figure: a cab without any driver position is not a single desk") { + cab_place const noseat{"interior/401da-207.t3d", std::nullopt, std::nullopt}; + CHECK_FALSE(single_desk(true, desk_401da, noseat)); + CHECK_FALSE(single_desk(true, noseat, desk_401da)); + CHECK_FALSE(single_desk(true, noseat, noseat)); +} + +TEST_CASE("driver figure: the seats count as one within a centimetre") { + auto cab2{desk_401da}; + cab2.sitting_position->x += 0.005f; + CHECK(single_desk(true, desk_401da, cab2)); + cab2.sitting_position->x += 0.02f; + CHECK_FALSE(single_desk(true, desk_401da, cab2)); +} + +TEST_CASE("driver figure: the figure of the occupied cab shows when it doesn't follow the direction") { + for (auto const direction : {-1, 0, 1}) { + CAPTURE(direction); + CHECK(shown(1, direction, false) == 1); + CHECK(shown(-1, direction, false) == -1); + } +} + +TEST_CASE("driver figure: following the direction, the figure faces the way the vehicle goes") { + CHECK(shown(1, 1, true) == 1); + CHECK(shown(1, -1, true) == -1); // the player reversing without changing the cab + CHECK(shown(-1, -1, true) == -1); // the cab changed, driving on in the cab's own direction + CHECK(shown(-1, 1, true) == 1); +} + +TEST_CASE("driver figure: without a direction selected the figure of the occupied cab shows") { + CHECK(shown(1, 0, true) == 1); + CHECK(shown(-1, 0, true) == -1); +} + +TEST_CASE("driver figure: no figure without an occupied cab") { + for (auto const follows : {false, true}) { + CAPTURE(follows); + CHECK(shown(0, 1, follows) == 0); + CHECK(shown(0, -1, follows) == 0); + CHECK(shown(0, 0, follows) == 0); + } +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index a5ac87be6..a4d5f6669 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -971,6 +971,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "driverfigure.followsdirection") + { + ParseOne(Parser, DriverFigureFollowsDirection, 1, false); + return true; + } + if (token == "ai.brakesetting.cw1") { ParseOne(Parser, AIBrakeSettingCw1, 1, false); @@ -2544,6 +2550,7 @@ global_settings::export_as_text( std::ostream &Output ) const { track_buckling == track_buckling_mode::automatic ? "auto" : "scenery" } ); export_as_text( Output, "ai.trainman", AITrainman ); + export_as_text( Output, "driverfigure.followsdirection", DriverFigureFollowsDirection ); export_as_text( Output, "controlcoupling.enginecheck", control_coupling_engine_check ); std::string couplerphysics { coupler_physics ? "yes" : "no" }; if( coupler_physics_all ) { diff --git a/utilities/Globals.h b/utilities/Globals.h index e5887be33..3364c49a0 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -168,6 +168,7 @@ struct global_settings { bool bJoinEvents{ false }; // czy grupować eventy o tych samych nazwach int iHiddenEvents{ 1 }; // czy łączyć eventy z torami poprzez nazwę toru bool AITrainman{ true }; // virtual assistant performing consist coupling/decoupling and other maintenance tasks + bool DriverFigureFollowsDirection{ true }; // driverfigure.followsdirection: the player's lowpoly driver figure in a single desk vehicle faces the selected direction, no: the occupied cab as before eu07/maszyna#535 bool AIBrakeSettingCw1{ true }; // ai.brakesetting.cw1: the AI wagon inspector sets the brakes (G/P/R/Mg) by the instruction Cw-1, no: as before eu07/maszyna#350 // ui int PythonScreenUpdateRate{ 200 }; // delay between python-based screen updates, in milliseconds diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 7eb6f19a9..fb28557a0 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -49,6 +49,7 @@ http://mozilla.org/MPL/2.0/. #include "model/MdlMngr.h" #include "model/Model3d.h" #include "vehicle/doorwings.h" +#include "vehicle/driverfigure.h" #include "rendering/renderer.h" #include "editor/editorTerrainStreamer.hpp" #include "application/uitranscripts.h" @@ -1305,9 +1306,16 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) && Mechanik != nullptr && Mechanik->action() != TAction::actSleep ) { // rysowanie figurki mechanika - btMechanik1.Turn(MoverParameters->CabOccupied > 0); - btMechanik2.Turn( MoverParameters->CabOccupied < 0 ); - if( MoverParameters->CabOccupied != 0 ) { + // a player driving a vehicle with a single desk is seen facing the selected direction of travel, as the AI + // is, which changes the cab instead (eu07/maszyna#535) + auto const followsdirection { + Global.DriverFigureFollowsDirection + && SingleDesk + && false == Mechanik->AIControllFlag }; + auto const figure { driver_figure::shown( MoverParameters->CabOccupied, MoverParameters->DirAbsolute, followsdirection ) }; + btMechanik1.Turn( figure > 0 ); + btMechanik2.Turn( figure < 0 ); + if( figure != 0 ) { btnOn = true; } } @@ -5911,6 +5919,38 @@ TDynamicObject::radius() const { return glm::length( diagonal ) * 0.5f; } +namespace { + +struct driver_position_key { + std::string_view token; + std::size_t cab; // 0 for the cab 1, 1 for the cab 2 + bool sitting; +}; + +constexpr std::array driver_position_keys{{ + {"driver1pos:", 0, false}, {"driver1sitpos:", 0, true}, {"driver2pos:", 1, false}, {"driver2sitpos:", 1, true}}}; + +// driverNpos: and driverNsitpos: of the cabs 1 and 2 of the internaldata: section, kept for the driver figures; any +// other token is left alone +void read_driver_position(cParser &Parser, std::string_view const Token, std::array &Cabs) { + auto const key{std::ranges::find(driver_position_keys, Token, &driver_position_key::token)}; + if (key == driver_position_keys.end()) { + return; + } + Parser.getTokens(3, false); + glm::vec3 position{0.f}; + Parser >> position.x >> position.y >> position.z; + auto &cab{Cabs[key->cab]}; + if (key->sitting) { + cab.sitting_position = position; + } + else { + cab.position = position; + } +} + +} // namespace + // McZapkie-250202 // wczytywanie pliku z danymi multimedialnymi (dzwieki) void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string const &ReplacableSkin ) { @@ -7430,6 +7470,7 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co } // locations: else if( token == "internaldata:" ) { + std::array cabplaces; // the cabs 1 and 2, for the driver figures // dalej nie czytaj do { // zbieranie informacji o kabinach @@ -7442,10 +7483,12 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co else if( token == "cab1model:" ) { parser.getTokens(); parser >> token; if( token != "none" ) { iCabs |= 0x1; } + cabplaces[ 0 ].model = token; } else if( token == "cab2model:" ) { parser.getTokens(); parser >> token; if( token != "none" ) { iCabs |= 0x4; } + cabplaces[ 1 ].model = token; } // engine sounds else if( token == "ignition:" ) { @@ -7788,9 +7831,14 @@ void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string co parser.getTokens(); parser >> DestinationSign.background; } + else { + read_driver_position( parser, token, cabplaces ); + } } while( token != "" ); + SingleDesk = driver_figure::single_desk( JointCabs, cabplaces[ 0 ], cabplaces[ 1 ] ); + } // internaldata: } while( token != "" ); diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index e5ea881e0..ca82a0950 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -247,6 +247,7 @@ public: TModel3d *mdLowPolyInt; // ABu 010305: wnetrze lowpoly std::array LowPolyIntCabs {}; // pointers to low fidelity version of individual driver cabs bool JointCabs{ false }; // flag for vehicles with multiple virtual 'cabs' sharing location and 3d model(s) + bool SingleDesk{ false }; // the joint cabs 1 and 2 are one desk: same model, same driver seat (driver figures, eu07/maszyna#535) std::vector mdAttachments; // additional models attached to main body struct destination_data { TSubModel *sign { nullptr }; // submodel mapped with replacable texture -4 diff --git a/vehicle/driverfigure.h b/vehicle/driverfigure.h new file mode 100644 index 000000000..5f25b39ae --- /dev/null +++ b/vehicle/driverfigure.h @@ -0,0 +1,70 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include + +// the driver figures of the lowpoly interior, mechanik1 and mechanik2, seen from outside the vehicle (eu07/maszyna#535). +// A vehicle with one desk for both directions (401Da, SM31, TEM2...) has two virtual cabs set up on the same spot, so +// the AI changes the cab to drive the other way and its figure turns round. The player usually stays in the cab and +// only moves the reverser, so in such a vehicle the player's figure follows the selected direction of travel instead. +namespace driver_figure { + +// what the .mmd says about one driver cab, as far as the figures go +struct cab_place { + std::string model; // cabNmodel:, empty when not given + std::optional position; // driverNpos: + std::optional sitting_position; // driverNsitpos: + + // where the driver sits: the sitting position, or the position when the cab gives no sitting position, the way + // the cab is loaded for the player + std::optional seat() const { + return sitting_position.has_value() ? sitting_position : position; + } +}; + +// how close the seats of the two cabs have to be to count as one seat, in metres +inline constexpr float seat_tolerance{0.01f}; + +// the cabs 1 and 2 of the vehicle are the same desk: the .mmd says they share the place and the model (jointcabs:), +// both name the same cab model and both seat the driver on the same spot. A vehicle with two desks in one cab (SM42, +// SP42) seats the driver on the other side of the cab for the other direction, and a vehicle with two cabs has them at +// its two ends, so neither of them is a single desk. +inline bool single_desk(bool const JointCabs, cab_place const &Cab1, cab_place const &Cab2) { + if (false == JointCabs || Cab1.model.empty() || Cab1.model == "none" || Cab1.model != Cab2.model) { + return false; + } + auto const seat1{Cab1.seat()}; + auto const seat2{Cab2.seat()}; + if (false == seat1.has_value() || false == seat2.has_value()) { + return false; + } + return glm::distance(*seat1, *seat2) <= seat_tolerance; +} + +// which of the figures shows: 1 for mechanik1, -1 for mechanik2, 0 for neither. +// Cab: the occupied cab (CabOccupied: 1, -1 or 0). +// Direction: the selected direction of travel against the couplers (DirAbsolute: 1, -1 or 0). +// FollowsDirection: the figure follows the direction rather than the cab, that is a player drives a single desk vehicle. +// Without a direction selected the figure of the occupied cab shows, as it always did. +inline int shown(int const Cab, int const Direction, bool const FollowsDirection) { + if (Cab == 0) { + return 0; + } + if (false == FollowsDirection || Direction == 0) { + return Cab > 0 ? 1 : -1; + } + return Direction > 0 ? 1 : -1; +} + +} // namespace driver_figure From 7533ecb93f72f04d43301c1848bd5ca86e345431 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 27 Nov 2026 23:51:18 +0100 Subject: [PATCH 3/7] ci(sonar): analyse a push to staging as the branch staging, next to master (#522) A push build reaches sonar.yml through workflow_run like a pull request does; until now every push was analysed as the main branch, as only master had push builds. The branch is now taken from the trusted event (workflow_run.event, head_repository, head_branch), not from the artifact: master is analysed as the main branch as before, staging with sonar.branch.name=staging, and any other push is refused instead of being analysed. Nothing runs for staging yet: build.yml builds on a push to master only. That change follows separately, once this file is on master, because workflow_run workflows run from the default branch: with build.yml first, the old sonar.yml would analyse staging as the main branch and replace master's analysis. --- .github/workflows/sonar.yml | 41 ++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 93475df19..58e852370 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -130,6 +130,9 @@ jobs: env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} REPO: ${{ github.repository }} + RUN_EVENT: ${{ github.event.workflow_run.event }} + RUN_REPO: ${{ github.event.workflow_run.head_repository.full_name }} + RUN_BRANCH: ${{ github.event.workflow_run.head_branch }} run: | set -euo pipefail cd "$GITHUB_WORKSPACE" @@ -137,7 +140,18 @@ jobs: echo "event=$event" >> "$GITHUB_OUTPUT" if [ "$event" != "pull_request" ]; then - echo "Branch build, no PR parameters." + # A push: the branch comes from the trusted event, not from the artifact. Only + # master and staging are pushed to with a build (build.yml); anything else is refused + # rather than analysed as a branch of its own. + if [ "$RUN_EVENT" != "push" ] || [ "$RUN_REPO" != "$REPO" ]; then + echo "::error::branch build that isn't a push to this repository ($RUN_EVENT, $RUN_REPO)" + exit 1 + fi + case "$RUN_BRANCH" in + master|staging) echo "branch=$RUN_BRANCH" >> "$GITHUB_OUTPUT" ;; + *) echo "::error::no analysis for a push to $RUN_BRANCH"; exit 1 ;; + esac + echo "Branch build of $RUN_BRANCH, no PR parameters." exit 0 fi @@ -189,11 +203,9 @@ jobs: --define sonar.pullrequest.branch=${{ steps.meta.outputs.head }} --define sonar.pullrequest.base=${{ steps.meta.outputs.base }} - # No sonar.branch.name here on purpose: branch analysis is a paid feature, - # and passing it would push the scanner onto that code path. Omitting it - # means this is a plain main-branch analysis, which the Free plan allows. + # master is the main branch of the SonarQube Cloud project: no sonar.branch.name. - name: SonarQube Cloud scan (main branch) - if: steps.meta.outputs.event != 'pull_request' + if: steps.meta.outputs.event != 'pull_request' && steps.meta.outputs.branch == 'master' uses: SonarSource/sonarqube-scan-action@fd88b7d7ccbaefd23d8f36f73b59db7a3d246602 # v6.0.0 env: SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} @@ -206,6 +218,25 @@ jobs: --define sonar.qualitygate.wait=true --define sonar.scm.revision=${{ github.event.workflow_run.head_sha }} + # staging as a branch of its own next to master, so its issues and its quality gate show + # before staging is merged into master. SonarQube Cloud keeps it as a long-lived branch + # only if its name matches the project's long-lived branch pattern (Administration > + # Branches and Pull Requests); otherwise it is a short-lived one, deleted when inactive. + - name: SonarQube Cloud scan (staging) + if: steps.meta.outputs.event != 'pull_request' && steps.meta.outputs.branch == 'staging' + uses: SonarSource/sonarqube-scan-action@fd88b7d7ccbaefd23d8f36f73b59db7a3d246602 # v6.0.0 + env: + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + SONAR_HOST_URL: https://sonarcloud.io + with: + args: > + --define sonar.cfamily.compile-commands=${{ env.BUILD_WRAPPER_OUT_DIR }}/compile_commands.json + --define sonar.cfamily.taintAnalysis=false + --define sonar.exclusions=${{ env.SONAR_EXCLUSIONS }} + --define sonar.qualitygate.wait=true + --define sonar.scm.revision=${{ github.event.workflow_run.head_sha }} + --define sonar.branch.name=staging + - name: Report success if: success() env: From 702b552780eec957e4a5b7e399a476b9ffc3f68e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 27 Nov 2026 23:51:25 +0100 Subject: [PATCH 4/7] fix(render): particle vertex attribute offsets from offsetof in the GL 4.6 and Vulkan renderers (#511) * fix(render): particle vertex attribute offsets from offsetof * fix(render): particle vertex attribute offsets from offsetof in the GL 4.6 and Vulkan renderers The GL 4.6 particles passed 0, 12 and 28 to setup_attrib, the Vulkan layout of vertex_kind::particle had the stride 36 and the same offsets as numbers. They now come from sizeof and offsetof of particle_vertex. The Vulkan particle_vertex moves from vulkan14frame.cpp to vulkan14context.h so the layout in vulkan14scene.cpp can use it. A build with static_asserts that each offsetof equals the old number (and the size 36) compiled; the asserts were taken out after. --- rendering/opengl46/opengl46particles.cpp | 8 +++++--- rendering/vulkan14/vulkan14context.h | 9 +++++++++ rendering/vulkan14/vulkan14frame.cpp | 8 +------- rendering/vulkan14/vulkan14scene.cpp | 8 +++++--- 4 files changed, 20 insertions(+), 13 deletions(-) diff --git a/rendering/opengl46/opengl46particles.cpp b/rendering/opengl46/opengl46particles.cpp index c9a78e217..22d0c5145 100644 --- a/rendering/opengl46/opengl46particles.cpp +++ b/rendering/opengl46/opengl46particles.cpp @@ -10,6 +10,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "rendering/opengl46/opengl46particles.h" +#include + #include "rendering/particles.h" #include "rendering/openglcamera.h" #include "simulation/simulation.h" @@ -109,9 +111,9 @@ opengl46_particles::render() { if (!m_vao) { m_vao.emplace(); - m_vao->setup_attrib(*m_buffer, 0, 3, GL_FLOAT, sizeof(particle_vertex), 0); - m_vao->setup_attrib(*m_buffer, 1, 4, GL_FLOAT, sizeof(particle_vertex), 12); - m_vao->setup_attrib(*m_buffer, 2, 2, GL_FLOAT, sizeof(particle_vertex), 28); + m_vao->setup_attrib(*m_buffer, 0, 3, GL_FLOAT, sizeof(particle_vertex), static_cast(offsetof(particle_vertex, position))); + m_vao->setup_attrib(*m_buffer, 1, 4, GL_FLOAT, sizeof(particle_vertex), static_cast(offsetof(particle_vertex, color))); + m_vao->setup_attrib(*m_buffer, 2, 2, GL_FLOAT, sizeof(particle_vertex), static_cast(offsetof(particle_vertex, texture))); gl::buffer::unbind(gl::buffer::ARRAY_BUFFER); gl::vao::unbind(); diff --git a/rendering/vulkan14/vulkan14context.h b/rendering/vulkan14/vulkan14context.h index 2bbca3551..f3ef48acc 100644 --- a/rendering/vulkan14/vulkan14context.h +++ b/rendering/vulkan14/vulkan14context.h @@ -68,6 +68,15 @@ enum class vertex_kind : std::uint8_t particle_instance // three vec4 of gl::particle_draw for each instance, the particles of the gpu }; +// the vertices of a particle of the smoke of the cpu (vertex_kind::particle, as opengl46_particles has them) +struct particle_vertex +{ + glm::vec3 position; + glm::vec4 color; + glm::vec2 texture; +}; +static_assert(sizeof(particle_vertex) == 36, "the layout of the vertices of the particles"); + // the push constants of the pipelines of the scene and of the post-processing (shaders/vk14/common.glsl, draw_constants_block) struct draw_constants { diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 9a033978a..e3ead2753 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -101,13 +101,7 @@ glm::mat4 ortho_frustumtest_projection(float l, float r, float b, float t, float glm::mat4 const coordmove{0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 1.0}; // the vertices of a particle of the smoke (opengl46_particles) -struct particle_vertex -{ - glm::vec3 position; - glm::vec4 color; - glm::vec2 texture; -}; -static_assert(sizeof(particle_vertex) == 36, "the layout of the vertices of the particles"); +using vk14::particle_vertex; std::vector> const billboard_vertices{ {{-0.5f, -0.5f, 0.f}, {0.f, 0.f}}, {{0.5f, -0.5f, 0.f}, {1.f, 0.f}}, {{0.5f, 0.5f, 0.f}, {1.f, 1.f}}, {{-0.5f, -0.5f, 0.f}, {0.f, 0.f}}, {{0.5f, 0.5f, 0.f}, {1.f, 1.f}}, {{-0.5f, 0.5f, 0.f}, {0.f, 1.f}}, diff --git a/rendering/vulkan14/vulkan14scene.cpp b/rendering/vulkan14/vulkan14scene.cpp index 75d580bb2..5f1b5d976 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -101,9 +101,11 @@ vk14::vertex_layout layout_of(vk14::vertex_kind const Kind) layout.attributes = {{0, 0, VK_FORMAT_R32G32B32A32_SFLOAT, 0}, {1, 0, VK_FORMAT_R32G32B32A32_SFLOAT, sizeof(glm::vec4)}}; break; case vk14::vertex_kind::particle: - // position, colour, texture coordinates (opengl46_particles::particle_vertex) - layout.bindings = {{0, 36, VK_VERTEX_INPUT_RATE_VERTEX}}; - layout.attributes = {{0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0}, {1, 0, VK_FORMAT_R32G32B32A32_SFLOAT, 12}, {2, 0, VK_FORMAT_R32G32_SFLOAT, 28}}; + // position, colour, texture coordinates + layout.bindings = {{0, sizeof(vk14::particle_vertex), VK_VERTEX_INPUT_RATE_VERTEX}}; + layout.attributes = {{0, 0, VK_FORMAT_R32G32B32_SFLOAT, static_cast(offsetof(vk14::particle_vertex, position))}, + {1, 0, VK_FORMAT_R32G32B32A32_SFLOAT, static_cast(offsetof(vk14::particle_vertex, color))}, + {2, 0, VK_FORMAT_R32G32_SFLOAT, static_cast(offsetof(vk14::particle_vertex, texture))}}; break; case vk14::vertex_kind::position_uv: layout.bindings = {{0, sizeof(glm::vec3), VK_VERTEX_INPUT_RATE_VERTEX}, {1, sizeof(glm::vec2), VK_VERTEX_INPUT_RATE_VERTEX}}; From d90fcea158212e2b759c79551ab38d774f7cfbb2 Mon Sep 17 00:00:00 2001 From: pawelw Date: Fri, 27 Nov 2026 23:51:33 +0100 Subject: [PATCH 5/7] refactor(ai): the decisions of an uphill start in uphill_start::, with unit tests of the release phase (#445) * refactor(ai): the decisions of an uphill start in uphill_start::, with unit tests of the release phase * refactor(ai): the grade force of an uphill start situation no longer named as the holding factor, std::array in its test * refactor(ai): the situation of an uphill start filled by field name, so the compiler checks the order --- tests/unit/test_uphill_start.cpp | 110 +++++++++++++++++++++++++++++++ vehicle/Driver.cpp | 74 ++++++++++----------- vehicle/Driver.h | 1 - vehicle/uphillstart.cpp | 31 +++++++++ vehicle/uphillstart.h | 36 ++++++++++ 5 files changed, 211 insertions(+), 41 deletions(-) diff --git a/tests/unit/test_uphill_start.cpp b/tests/unit/test_uphill_start.cpp index d450af68b..e487fc703 100644 --- a/tests/unit/test_uphill_start.cpp +++ b/tests/unit/test_uphill_start.cpp @@ -101,3 +101,113 @@ TEST_CASE("uphill start: once ended, the top-up stays ended for the start") { state = {}; CHECK(brake_top_up(state, 0.5 * grade, grade, 1.5, application, application) == top_up_action::step); } + +// the rest of a start: when it begins, when it is given up, when the train brake may be released, when the release +// phase is over and how much power is applied against the releasing brake + +namespace { + +// the ST43 train standing at the signal on its train brake, asked to go +uphill_start::situation standing_train() { + uphill_start::situation now; + now.standing = true; + now.speed_up = true; + now.speed_asked = true; + now.train_brake_applied = true; + now.grade_force = grade; + return now; +} + +} // namespace + +TEST_CASE("uphill start: begins with the whole train at a stand on the train brake, asked to go") { + auto now{standing_train()}; + CHECK(uphill_start::begins(now)); + SUBCASE("not while the head stands for a moment and the train rolls back") { + now.consist_velocity = -0.8; + CHECK_FALSE(uphill_start::begins(now)); + } + SUBCASE("not without the train brake to hold the train") { + now.train_brake_applied = false; + CHECK_FALSE(uphill_start::begins(now)); + } + SUBCASE("not before the brakes of the train are charged") { + now.consist_charged = false; + CHECK_FALSE(uphill_start::begins(now)); + } + SUBCASE("not when not asked to go") { + now.speed_up = false; + CHECK_FALSE(uphill_start::begins(now)); + now.speed_up = true; + now.speed_asked = false; + CHECK_FALSE(uphill_start::begins(now)); + } + SUBCASE("not under way") { + now.standing = false; + CHECK_FALSE(uphill_start::begins(now)); + } +} + +TEST_CASE("uphill start: given up when the train as a whole rolls back, not its head") { + auto now{standing_train()}; + // the locomotive runs back into the slack, the rest of the train stands + now.velocity = -1.0; + now.consist_velocity = -0.1; + CHECK_FALSE(uphill_start::rolls_back(now)); + now.consist_velocity = -0.6; + CHECK(uphill_start::rolls_back(now)); +} + +TEST_CASE("uphill start: the train brake is released once the power holds the train") { + auto now{standing_train()}; + now.tractive_force = 1.05 * grade; + CHECK_FALSE(uphill_start::power_holds(now, 10.0)); + now.tractive_force = 1.15 * grade; + CHECK(uphill_start::power_holds(now, 10.0)); + SUBCASE("or the train is under way") { + now.tractive_force = 0.5 * grade; + now.velocity = 1.2; + CHECK(uphill_start::power_holds(now, 10.0)); + } + SUBCASE("or a locomotive that can't hold the train has had its time") { + now.tractive_force = 0.5 * grade; + CHECK_FALSE(uphill_start::power_holds(now, uphill_start::hold_time - 1.0)); + CHECK(uphill_start::power_holds(now, uphill_start::hold_time + 1.0)); + } +} + +TEST_CASE("uphill start: the release phase ends when the brakes are off, or after its time") { + auto now{standing_train()}; + CHECK_FALSE(uphill_start::released(now, 30.0)); + now.consist_released = true; + CHECK(uphill_start::released(now, 30.0)); + SUBCASE("a brake that doesn't come off ends it all the same") { + now.consist_released = false; + CHECK_FALSE(uphill_start::released(now, uphill_start::release_time - 1.0)); + CHECK(uphill_start::released(now, uphill_start::release_time + 1.0)); + } +} + +TEST_CASE("uphill start: against the releasing brake no more power is added than holds the train") { + // outside the release phase the start doesn't limit the power + CHECK(uphill_start::may_add_power(false, 3.0 * grade, grade)); + CHECK(uphill_start::may_add_power(true, 1.05 * grade, grade)); + CHECK_FALSE(uphill_start::may_add_power(true, 1.15 * grade, grade)); +} + +TEST_CASE("uphill start: on coarse notches the power stays on the first one that holds the train") { + // an EU07 at a standstill on 3 kV gives about 29, 52, 79 and 104 kN on notches 1-4 (eu07/maszyna#396): with a + // train of 300 t on 10 per mille, 29.4 kN of grade force, notch 2 jumps from 0.99 to 1.77 x the grade force + std::array const notches{29000.0, 52000.0, 79000.0, 104000.0}; + double const holding{300000.0 * 9.81 * 0.01}; + auto notch{0}; + auto force{0.0}; + // in the release phase, a notch added an update as long as power may be added + for (auto update{0}; update < 10; ++update) { + if (uphill_start::may_add_power(true, force, holding) && (notch < static_cast(notches.size()))) { + force = notches[notch++]; + } + } + CHECK(notch == 2); + CHECK(force / holding == doctest::Approx(1.77).epsilon(0.01)); +} diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 4b8a68ed4..554d304cc 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -8945,10 +8945,8 @@ void TController::control_tractive_force() { if( AccDesired > EU07_AI_NOACCELERATION // don't add power if not asked for actual speed-up && (AbsAccS < AccDesired /*- std::min( 0.05, 0.01 * iDriverFailCount )*/ || mvOccupied->SpeedCtrlUnit.IsActive && velocity < mvOccupied->SpeedCtrlUnit.FullPowerVelocity) && false == TestFlag(iDrivigFlags, movePress) && - // starting uphill against the releasing brake, the power that holds the train is enough: the brake coming off - // speeds the train up, more power only drags the brake and slips the wheels. nor is a notch past that taken - // back: the power got there in one notch from below, and the notch below doesn't hold the train - ( false == bUphillRelease || fUphillTractiveForce < uphill_start::holding_force * fUphillHoldingForce ) && + // starting uphill against the releasing brake, no more power than holds the train + uphill_start::may_add_power( bUphillRelease, fUphillTractiveForce, fUphillHoldingForce ) && // nor while the train brake is still being applied further to hold the train false == bUphillBrakeTopUp && velocity < (VelDesired == 1.0 ? // work around for trains getting stuck on tracks with speed limit = 1 @@ -9010,41 +9008,42 @@ void TController::control_uphill_start() { end_uphill_start(); return; } - if( false == bUphillStart ) { - if( ( std::abs( velocity ) < EU07_AI_NOMOVEMENT ) - // the whole train at a stand, not only its head stopped for a moment while the train rolls back - && ( fConsistVelocity > -0.5 ) - && ( AccDesired > EU07_AI_NOACCELERATION ) - && ( VelDesired > 0.0 ) - && ( BrakeCtrlPosition > 0.0 ) // only with the train brake still applied to hold the train - && ( IsConsistCharged ) ) { // and charged to what the pipe has, or the brake that holds the train has no air - bUphillStart = true; - bUphillRelease = false; - UphillTopUp = {}; - fUphillStartTime = ElapsedTime; - } - else { - return; - } - } - if( AccDesired <= EU07_AI_NOACCELERATION ) { - // no longer to start: the standing rules take over - end_uphill_start(); - return; - } - if( fConsistVelocity < -0.5 ) { - // the train rolls back all the same: the rules for a train slipping back take over and apply the brakes. - // the train as a whole, not its head: with the locomotive brake off, the locomotive and the first vehicles - // run back into the slack of a long train still held by its brake - end_uphill_start(); - return; - } fUphillTractiveForce = 0.0; for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { // Ft is signed in the vehicle's own frame, and turned into the direction of travel as AbsAccS is fUphillTractiveForce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); } fUphillHoldingForce = fMass * -fAccGravity; + uphill_start::situation const now { + .standing = std::abs( velocity ) < EU07_AI_NOMOVEMENT, + .velocity = velocity, + .consist_velocity = fConsistVelocity, + .speed_up = AccDesired > EU07_AI_NOACCELERATION, + .speed_asked = VelDesired > 0.0, + .train_brake_applied = BrakeCtrlPosition > 0.0, + .tractive_force = fUphillTractiveForce, + .grade_force = fUphillHoldingForce, + .consist_released = IsConsistReleased, + .consist_charged = IsConsistCharged }; + if( false == bUphillStart ) { + if( false == uphill_start::begins( now ) ) { + return; + } + bUphillStart = true; + bUphillRelease = false; + UphillTopUp = {}; + fUphillStartTime = ElapsedTime; + } + if( false == now.speed_up ) { + // no longer to start: the standing rules take over + end_uphill_start(); + return; + } + if( uphill_start::rolls_back( now ) ) { + // the rules for a train slipping back take over and apply the brakes + end_uphill_start(); + return; + } bUphillBrakeTopUp = false; if( false == bUphillRelease ) { bUphillBrakeTopUp = uphill_brake_top_up(); @@ -9055,10 +9054,7 @@ void TController::control_uphill_start() { && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { cue_action( driver_hint::independentbrakerelease ); } - if( ( velocity > 1.0 ) - || ( fUphillTractiveForce > uphill_start::holding_force * fUphillHoldingForce ) - // a locomotive that can't hold the train on its own power gets the brake off in the end all the same - || ( ElapsedTime - fUphillStartTime > 45.0 ) ) { + if( uphill_start::power_holds( now, ElapsedTime - fUphillStartTime ) ) { // the power holds the train: the train brake can be released bUphillRelease = true; fUphillReleaseTime = ElapsedTime; @@ -9067,9 +9063,7 @@ void TController::control_uphill_start() { } // the train brake is being released with the power on. the start ends once the brakes are off: ended before, // the brake still on takes the power off, the train rolls back and has to be braked to a stand again - if( IsConsistReleased - // a brake that doesn't come off (a hand brake) ends it all the same - || ( ElapsedTime - fUphillReleaseTime > EU07_AI_UPHILLRELEASETIME ) ) { + if( uphill_start::released( now, ElapsedTime - fUphillReleaseTime ) ) { end_uphill_start(); } } diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 0eae2caf1..0fc445ce3 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -30,7 +30,6 @@ auto const EU07_AI_BRAKINGTESTACCELERATION = -0.06; auto const EU07_AI_NOMOVEMENT = 0.05; // standstill velocity threshold auto const EU07_AI_MOVEMENT = 1.0; // deliberate movement velocity threshold auto const EU07_AI_UPHILLGRAVITY = -0.025; // [m/s2] about 2.5 per mille up: the gradient that rolls a standing train back -auto const EU07_AI_UPHILLRELEASETIME = 60.0; // [s] the longest an uphill start keeps the power on while the train brake releases auto const EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE = 10000.0; auto const EU07_AI_SANDEDSTARTVELOCITY = 15.0; // [km/h] a start that slipped keeps the sand on up to this speed diff --git a/vehicle/uphillstart.cpp b/vehicle/uphillstart.cpp index dd1895b11..534839093 100644 --- a/vehicle/uphillstart.cpp +++ b/vehicle/uphillstart.cpp @@ -12,6 +12,37 @@ http://mozilla.org/MPL/2.0/. namespace uphill_start { +bool begins(situation const &Now) { + + return Now.standing + // the whole train at a stand, not only its head stopped for a moment while the train rolls back + && (Now.consist_velocity > rollback_velocity) && Now.speed_up && Now.speed_asked + // only with the train brake still applied to hold the train + && Now.train_brake_applied + // and charged to what the pipe has, or the brake that holds the train has no air + && Now.consist_charged; +} + +bool rolls_back(situation const &Now) { + + return Now.consist_velocity < rollback_velocity; +} + +bool power_holds(situation const &Now, double const Holdtime) { + + return (Now.velocity > moving_velocity) || (Now.tractive_force > holding_force * Now.grade_force) || (Holdtime > hold_time); +} + +bool released(situation const &Now, double const Releasetime) { + + return Now.consist_released || (Releasetime > release_time); +} + +bool may_add_power(bool const Releasing, double const Tractiveforce, double const Holdingforce) { + + return (false == Releasing) || (Tractiveforce < holding_force * Holdingforce); +} + top_up_action brake_top_up( top_up &State, double const Brakeforce, double const Holdingforce, double const Brakeposition, double const Heldtime, double const Applicationtime) { diff --git a/vehicle/uphillstart.h b/vehicle/uphillstart.h index 108662cbe..687934990 100644 --- a/vehicle/uphillstart.h +++ b/vehicle/uphillstart.h @@ -20,6 +20,42 @@ auto const top_up_position{4.0}; // full service: the furthest the train brake i // a step that adds less brake force than this, as a multiple of the grade force, is the last one auto const top_up_gain{0.02}; +auto const hold_time{45.0}; // [s] a locomotive that can't hold the train on its own power gets the brake off after it all the same +auto const release_time{60.0}; // [s] the longest the power stays on against the releasing brake (a hand brake doesn't come off) +auto const rollback_velocity{-0.5}; // [km/h] the train as a whole rolling back faster than this gives a start up +auto const moving_velocity{1.0}; // [km/h] the head of the train going forward faster than this is under way + +// what a start goes by, at a moment +struct situation { + bool standing{false}; // the head of the train at a stand + double velocity{0.0}; // of the head of the train, in the direction of travel [km/h] + // of the whole train, mass-weighted, in the direction of travel [km/h]: with the locomotive brake off, the + // locomotive and the first vehicles run back into the slack of a long train still held by its brake + double consist_velocity{0.0}; + bool speed_up{false}; // the driver is asked to speed up + bool speed_asked{false}; // there is a speed to go at + bool train_brake_applied{false}; // the train brake handle is past running + double tractive_force{0.0}; // of the train, in the direction of travel [N] + double grade_force{0.0}; // the grade force on the train [N] + bool consist_released{false}; // the brakes of the train are off, the hold of the start not counted + // the brakes of the train charged to what the pipe has: else the brake that holds the train has no air + bool consist_charged{true}; +}; + +// a start begins: the whole train at a stand on the train brake, charged, and asked to go +bool begins(situation const &Now); +// the train rolls back all the same: the rules for a train slipping back take over +bool rolls_back(situation const &Now); +// the power holds the train, so the train brake can be released. Holdtime: since the start began, or since the last +// step of the top-up [s] +bool power_holds(situation const &Now, double Holdtime); +// the release phase is over: the brakes are off, or they don't come off. Releasetime: since it began [s] +bool released(situation const &Now, double Releasetime); +// power may be added. against the releasing brake, the power that holds the train is enough: the brake coming off +// speeds the train up, more power only drags the brake and slips the wheels. nor is a notch past that taken back: +// the power got there in one notch from below, and the notch below doesn't hold the train +bool may_add_power(bool Releasing, double Tractiveforce, double Holdingforce); + // what has been done to apply the train brake further, in one start struct top_up { double last_force{-1.0}; // the brake force when the last step was given, -1 before the first [N] From 1a12c7ef4ff1ad7ed796286ce8120ee00543a9fe Mon Sep 17 00:00:00 2001 From: pawelw Date: Fri, 27 Nov 2026 23:51:42 +0100 Subject: [PATCH 6/7] fix(events): say in the log when a condition passes because it can't test, and when a call is dropped (#448) * fix(events): say in the log when a condition passes because it can't test, and when a call is dropped A condition which can't do its test passes, and nothing told the scenery author. Now the log says so when the scenery loads: - trackfree / trackoccupied with no target, or with a target that isn't a track (an isolated section, a memory cell): the track test passes every time; - a word in a condition the reader doesn't know, such as a name written after trackfree: it's skipped; - a multiple comparing a memory cell that doesn't exist: besides the cell (already logged), that its whole memcompare condition is off and it always runs the events before its else. And log.txt says when an event called while it's still in the queue isn't added again, with the vehicle of the lost call and of the queued one. Nothing changes in how events run. * fix(events): log a lost call once per stay in the queue, set the activator of a joint event A standing vehicle queues its event0 / eventall0 every frame, so an event with a delay logged "EVENT ALREADY IN QUEUE" once a frame until it ran (65 thousand lines in 70 s of a train standing on such a track). Now a lost call is logged only when it comes from another vehicle than the one which queued the event, and once per stay in the queue. An instant event handing over to its joint (same-name) event queued that event with the vehicle of its previous run. It gets the vehicle of the call now, which it runs with and which the log names. The message about a missing memory cell says that only the memcompare test is off, and that the event always runs the events before its else only when no track or probability test is left. * fix(events): don't log a lost call from another vehicle of the same train A standing train calls its eventall0 from every vehicle, so the second vehicle's call was logged once per stay in the queue, and as the line is written once per stay, it could hide a lost call of another train standing on another track with the same event. A call from a vehicle coupled to the one which queued the event isn't logged now. * test(events): the unknown word in a condition is logged with the event and skipped A name written after trackfree is read as a word the condition reader doesn't know: one line in the log names the event and the word, and only the track test is set. The known words of a condition log nothing. * test(events): turn the log capture off when a case stops at a failed REQUIRE --- tests/unit/test_event_conditions.cpp | 44 ++++++++++++++++++- world/Event.cpp | 66 +++++++++++++++++++++------- world/Event.h | 6 ++- world/eventconditions.cpp | 9 +++- 4 files changed, 106 insertions(+), 19 deletions(-) diff --git a/tests/unit/test_event_conditions.cpp b/tests/unit/test_event_conditions.cpp index 81a55201b..d7c1b8e12 100644 --- a/tests/unit/test_event_conditions.cpp +++ b/tests/unit/test_event_conditions.cpp @@ -5,7 +5,15 @@ #include "utilities/parser.h" #include "world/Event.h" +#include +#include #include +#include +#include + +// the lines logged while capture is on, kept by the engine stubs (engine_stubs.cpp) +void unit_tests_log_capture(bool Enabled); +std::vector unit_tests_logged_lines(); // the condition block of the multiple and updatevalues events (world/eventconditions.cpp): the scenery editor writes // the conditions of the events back with export_as_text(), and what it writes has to read back as the same conditions @@ -18,13 +26,22 @@ struct event_kind : basic_event { }; using conditions = event_kind::event_conditions; +// the log capture is on while the object lives, so a failed REQUIRE doesn't leave it on for the cases after it +class log_capture { +public: + log_capture() { unit_tests_log_capture(true); } + ~log_capture() { unit_tests_log_capture(false); } + log_capture(log_capture const &) = delete; + log_capture &operator=(log_capture const &) = delete; +}; + // the conditions of an event text, read the way the events read them: the parser stands on the word 'condition' conditions read(std::string const &Text) { cParser parser(Text, cParser::buffer_TEXT); parser.getTokens(); REQUIRE(parser.peek() == "condition"); conditions result; - result.deserialize(parser); + result.deserialize(parser, "test"); // the reading stops at the next keyword of the event and leaves it for the event CHECK(parser.peek() == "endevent"); return result; @@ -128,3 +145,28 @@ TEST_CASE("event conditions: the track and probability conditions read back alon TEST_CASE("event conditions: an event without conditions writes none") { CHECK(write(conditions{}).empty()); } + +TEST_CASE("event conditions: a word the reader doesn't know is logged with the event and skipped") { + log_capture const capture; + // a name after trackfree: the track test takes the targets of the event, the name is skipped + auto const result{read("condition trackfree SomeTrack endevent")}; + auto lines{unit_tests_logged_lines()}; + + CHECK(result.flags == basic_event::flags::track_free); + REQUIRE(lines.size() == 1); + // the parser may give the word in lower case + auto &line{lines.front()}; + std::ranges::transform(line, line.begin(), [](unsigned char const Char) { return static_cast(std::tolower(Char)); }); + CHECK(line.find("\"test\"") != std::string::npos); + CHECK(line.find("\"sometrack\"") != std::string::npos); + CHECK(line.find("unknown word") != std::string::npos); +} + +TEST_CASE("event conditions: the known words log nothing") { + log_capture const capture; + auto const result{read("condition trackoccupied probability 0.5 memcompareex any == 1 * * endevent")}; + auto const lines{unit_tests_logged_lines()}; + + CHECK(result.flags == (basic_event::flags::track_busy | basic_event::flags::probability | basic_event::flags::text)); + CHECK(lines.empty()); +} diff --git a/world/Event.cpp b/world/Event.cpp index 814cd9918..ba51d4078 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -35,6 +35,8 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "widgets/map_objects.h" +#include + void basic_event::event_conditions::bind( basic_event::node_sequence *Nodes ) { @@ -42,19 +44,25 @@ basic_event::event_conditions::bind( basic_event::node_sequence *Nodes ) { } void -basic_event::event_conditions::init() { +basic_event::event_conditions::init( std::string_view const Eventname ) { tracks.clear(); - if( flags & ( flags::track_busy | flags::track_free ) ) { - for( auto &target : *memcompare_cells ) { - tracks.emplace_back( simulation::Paths.find( std::get( target ) ) ); - if( tracks.back() == nullptr ) { - // legacy compatibility behaviour, instead of disabling the event we disable the memory cell comparison test -// m_ignored = true; // deaktywacja -// ErrorLog( "Bad event: track \"" + std::get( target ) + "\" referenced in event \"" + asName + "\" doesn't exist" ); - flags &= ~( flags::track_busy | flags::track_free ); // zerowanie flag - } + if( ( flags & ( flags::track_busy | flags::track_free ) ) == 0 ) { + return; + } + auto const *testname { ( flags & flags::track_free ) != 0 ? "trackfree" : "trackoccupied" }; + if( memcompare_cells->empty() ) { + // the test goes over the targets of the event, so with none it has nothing to test and passes + ErrorLog( std::format( "Bad event: \"{}\" has no track to test with {}, so this test passes every time", Eventname, testname ) ); + } + for( auto &target : *memcompare_cells ) { + tracks.emplace_back( simulation::Paths.find( std::get( target ) ) ); + if( tracks.back() == nullptr ) { + // legacy compatibility behaviour, instead of disabling the event we disable the memory cell comparison test +// m_ignored = true; // deaktywacja + ErrorLog( std::format( "Bad event: \"{}\" can't test \"{}\" with {}, it isn't a track (an isolated section isn't one either), so this test passes every time", Eventname, std::get( target ), testname ) ); + flags &= ~( flags::track_busy | flags::track_free ); // zerowanie flag } } } @@ -364,7 +372,7 @@ updatevalues_event::init() { init_targets( simulation::Memory, "memory cell" ); // conditional data m_conditions.bind( &m_targets ); - m_conditions.init(); + m_conditions.init( m_name ); } // event type string @@ -400,7 +408,7 @@ updatevalues_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpa && false == is_keyword(token) ) { if( token == "condition" ) { - m_conditions.deserialize( Input ); + m_conditions.deserialize( Input, m_name ); // NOTE: condition deserialization leaves preloaded next token } } @@ -1174,12 +1182,22 @@ multi_event::init() { init_targets( simulation::Memory, "memory cell", conditiontchecksmemcell ); if( m_ignored ) { // legacy compatibility behaviour, instead of disabling the event we disable the memory cell comparison test + if( conditiontchecksmemcell + && std::ranges::any_of( m_targets, []( basic_node const &Target ) { return std::get( Target ) == nullptr; } ) ) { + // init_targets() named the missing cell; say what it does to the event, as it isn't what the scenery asks for + // the track and probability tests still apply, only the comparison is off + auto const otherconditions { ( m_conditions.flags & ( flags::track_busy | flags::track_free | flags::probability ) ) != 0 }; + ErrorLog( std::format( + "Bad event: \"{}\" compares a memory cell which doesn't exist, so its memcompare test is off{}", + m_name, + otherconditions ? std::string() : " and it always runs the events before its else" ) ); + } m_conditions.flags &= ~( flags::text | flags::value1 | flags::value2 ); m_ignored = false; } // conditional data m_conditions.bind( &m_targets ); - m_conditions.init(); + m_conditions.init( m_name ); // child events bindings for( auto &childevent : m_children ) { std::get( childevent ) = simulation::Events.FindEvent( std::get( childevent ) ); @@ -1247,7 +1265,7 @@ multi_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) { && false == is_keyword(token) ) { if( token == "condition" ) { - m_conditions.deserialize( Input ); + m_conditions.deserialize( Input, m_name ); // NOTE: condition block comes last so we can bail out afterwards break; } @@ -2449,7 +2467,22 @@ bool event_manager::AddToQuery( basic_event *Event, TDynamicObject const *Owner, double delay ) { if( Event->m_passive ) { return false; } // jeśli może być dodany do kolejki (nie używany w skanowaniu) - if( Event->m_inqueue > 0 ) { return false; } // jeśli nie dodany jeszcze do kolejki + if( Event->m_inqueue > 0 ) { // jeśli nie dodany jeszcze do kolejki + // a call of another train is lost, the event runs once, for whoever queued it first. + // logged once per stay in the queue, as a standing vehicle repeats its event0 call every frame, + // and not for the other vehicles of the same train, which repeat its eventall0 call + if( Owner != Event->m_activator + && false == Event->m_lostcalllogged + && false == ( Owner != nullptr && Owner->is_connected( Event->m_activator ) ) ) { + Event->m_lostcalllogged = true; + WriteLog( std::format( + "EVENT ALREADY IN QUEUE, NOT ADDED{}: {}{}", + Owner ? " by " + Owner->asName : std::string(), + Event->m_name, + Event->m_activator ? " (queued by " + Event->m_activator->asName + ")" : std::string() ) ); + } + return false; + } // kolejka eventów jest posortowana względem (fStartTime) Event->m_activator = Owner; @@ -2470,6 +2503,8 @@ event_manager::AddToQuery( basic_event *Event, TDynamicObject const *Owner, doub if( Event != nullptr && false == Event->m_ignored ) { // standardowe dodanie do kolejki + Event->m_activator = Owner; // a joint event reached above still holds the vehicle of its previous run + Event->m_lostcalllogged = false; ++Event->m_inqueue; // zabezpieczenie przed podwójnym dodaniem do kolejki WriteLog( "EVENT ADDED TO QUEUE" + ( Owner ? " by " + Owner->asName : "" ) + ": " + Event->m_name ); Event->m_launchtime = delay + std::abs( Event->m_delay ) + Timer::GetTime(); // czas od uruchomienia scenerii @@ -2544,6 +2579,7 @@ event_manager::CheckQuery() { QueryRootEvent->m_launchtime = m_workevent->m_launchtime; // czas musi być ten sam, bo nie jest aktualizowany QueryRootEvent->m_activator = m_workevent->m_activator; // pojazd aktywujący QueryRootEvent->m_inqueue = 1; + QueryRootEvent->m_lostcalllogged = false; // w sumie można by go dodać normalnie do kolejki, ale trzeba te połączone posortować wg czasu wykonania } else // a jak nazwa jest unikalna, to kolejka idzie dalej diff --git a/world/Event.h b/world/Event.h index c86fb8275..91ed85973 100644 --- a/world/Event.h +++ b/world/Event.h @@ -97,6 +97,7 @@ public: bool m_ignored { false }; // replacement for tp_ignored bool m_passive { false }; // false gdy ma nie być dodawany do kolejki (skanowanie sygnałów) int m_inqueue { 0 }; // ile razy dodany do kolejki + bool m_lostcalllogged { false }; // a lost call was already logged during the current stay in the queue TDynamicObject const *m_activator { nullptr }; double m_launchtime { 0.0 }; double m_delay { 0.0 }; @@ -122,9 +123,10 @@ protected: std::vector tracks; // used by conditional_track bool has_else { false }; - void deserialize( cParser &Input ); + // the event name only goes to the log, for the faults found in the condition + void deserialize( cParser &Input, std::string_view Eventname ); void bind( basic_event::node_sequence *Nodes ); - void init(); + void init( std::string_view Eventname ); // verifies whether event meets execution condition(s) bool test() const; // sends basic content of the class in legacy (text) format to provided stream diff --git a/world/eventconditions.cpp b/world/eventconditions.cpp index a091746e6..158f58dc0 100644 --- a/world/eventconditions.cpp +++ b/world/eventconditions.cpp @@ -12,6 +12,9 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "world/Event.h" +#include "utilities/Logs.h" + +#include bool basic_event::is_keyword( std::string const &Token ) { @@ -22,7 +25,7 @@ basic_event::is_keyword( std::string const &Token ) { } void -basic_event::event_conditions::deserialize( cParser &Input ) { +basic_event::event_conditions::deserialize( cParser &Input, std::string_view const Eventname ) { // przetwarzanie warunków, wspólne dla Multiple i UpdateValues std::string token; @@ -94,6 +97,10 @@ basic_event::event_conditions::deserialize( cParser &Input ) { flags |= flags::value2; } } + else { + // e.g. a name written after trackfree: the track test takes the targets of the event, never a name of its own + ErrorLog( std::format( "Bad event: \"{}\" has an unknown word \"{}\" in its condition, it's skipped", Eventname, token ) ); + } } } From b7f2186a19459285fdab8ce309b83d8b6e4ab807 Mon Sep 17 00:00:00 2001 From: pol102 Date: Fri, 27 Nov 2026 23:51:50 +0100 Subject: [PATCH 7/7] fix(audio): the sound comes back after the output device is lost or changed (#433) * fix(audio): the sound comes back after the output device is lost or changed Pulling out the headphones, or changing the output in the system, could leave the game silent until it was restarted, also after the very same output came back. The renderer learned about the output only from the events of the system (ALC_SOFT_system_events), and the check of the connection ran only without them. But: - the system doesn't report every loss. A stream invalidated without the device being removed and without another default output (a jack pulled out of a shared output, a change of the format, exclusive mode taken by another program) only marks the device as disconnected. Nothing looked at that, so nothing reopened it; - alcReopenDeviceSOFT returns ALC_TRUE also when the new output was opened but failed to start, which happens when the default output is reported before it is ready. The log said "reopened", the device stayed dead; - a reopen that failed was never tried again, in spite of "(will retry)" in the log; - with a device set in eu07.ini (sound.openal.renderer) nothing was followed at all: once that device lost its output it stayed silent, and a device absent at the start meant no sound for the whole session. Now the connection of the device is checked once a second next to the events, a removed device has it checked at once, a reopen counts only if the device is connected afterwards, and a failed one is tried again after 0.5, 1, 2, 4 and then every 4 s, and at once when the system reports any change. A device set in eu07.ini is left alone while it works; when it is lost it is opened again, the default output stands in for it while it is absent (also at the start), and the playback moves back when it returns. The failure is logged once per loss. The decisions are in audio::output_follower (audio/outputfollow.h), free of OpenAL, with unit tests. The time is the real one (steady_clock) rather than the simulation's, which stands still in pause and runs faster with time acceleration. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01QRgQ1GsKSGmguyc4rhvXWy * Revert "fix(physicslog): no road-vehicle logs, formatting on the writer, a slow disk and the closing kept short (#408)" This reverts commit d6c35935209a7e5b67c5a5030f660704ee91ca6f. * fix(audio): no gaps from devices that aren't the one set, the move back retried, rarer attempts after a minute Answers the review of #433: - A move back to the device set in eu07.ini that opened but didn't start left no output at all (the library lets go of the default output before it tries the other one). The default output is opened again at once. - The device set in eu07.ini is tried only when the library lists it, so a device of any other kind coming (USB, Bluetooth, HDMI of a monitor) no longer breaks the sound for a moment. - With no output at all the attempts thin out to every 30 s after the first minute. An event of the system still has one made at once, but not sooner than 250 ms after the last one, as a device coming reports a burst. And two faults found on the way: - A device name with Polish letters, written in code page 1250 by the starter, was never found again once the device had been absent: it was passed to the library as it was. It is matched as 1250 text too, with or without the "OpenAL Soft on " prefix of the library. - A move back that failed (the device reported before it was ready) wasn't tried again until another device came. It is tried again after 1, 2 and 4 s. Co-Authored-By: Claude Opus 5.5 * feat(audio): the log says which OpenAL library the game got and whether the sound follows the output with it At the start the game writes one line naming the OpenAL library it plays through, its version and the file it was loaded from (OpenAL32.dll of the game folder or of the system). With OpenAL Soft 1.23 or newer the line says the sound follows the default output of the system, or the device set in eu07.ini (sound.openal.renderer). With an older one, such as the 1.18.1 the game folder still has, nothing changes: the sound stays on the device opened at the start, and the line says why and what library follows the output. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Co-authored-by: jerrrrycho --- audio/audiorenderer.cpp | 277 +++++++++++++++++++++++++------ audio/audiorenderer.h | 24 ++- audio/outputfollow.h | 154 +++++++++++++++++ tests/unit/test_audio_output.cpp | 259 +++++++++++++++++++++++++++++ 4 files changed, 658 insertions(+), 56 deletions(-) create mode 100644 audio/outputfollow.h create mode 100644 tests/unit/test_audio_output.cpp diff --git a/audio/audiorenderer.cpp b/audio/audiorenderer.cpp index 16b24072b..2323c6b82 100644 --- a/audio/audiorenderer.cpp +++ b/audio/audiorenderer.cpp @@ -75,11 +75,21 @@ std::optional switch_value( std::string_view const Name ) { return std::nullopt; } +// returns: name of an output device without the prefix OpenAL Soft may put before the names of the devices it lists on +// Windows. it opens a device named either way, so the name in eu07.ini can come with it or without +std::string_view bare_output_name( std::string_view const Name ) { + + constexpr std::string_view prefix { "OpenAL Soft on " }; + return Name.starts_with( prefix ) ? Name.substr( prefix.size() ) : Name; +} + // opens the output device of sound.openal.renderer. the library names devices in UTF-8, but the starter writes eu07.ini // in code page 1250, so a name that fails as written is tried as 1250 text too. a device found neither way, unplugged -// say, leaves the default one rather than no sound at all. the name is set to what got opened, for a later reopen -ALCdevice *open_output_device() { +// say, leaves the default one rather than no sound at all: Fallback is set then, and the name stays as it is, for +// follow_output() to go back to that device once it's there again. the name is set to what got opened, for a later reopen +ALCdevice *open_output_device( bool &Fallback ) { + Fallback = false; if( Global.AudioRenderer.empty() ) { return ::alcOpenDevice( nullptr ); } @@ -92,8 +102,8 @@ ALCdevice *open_output_device() { return device; } } - ErrorLog( std::format( "sound: audio device \"{}\" not found, the default one used", Global.AudioRenderer ) ); - Global.AudioRenderer.clear(); + ErrorLog( std::format( "sound: audio device \"{}\" set in eu07.ini isn't available, using the default one", Global.AudioRenderer ) ); + Fallback = true; return ::alcOpenDevice( nullptr ); } @@ -108,6 +118,25 @@ std::vector split_name_list( ALCchar const *List ) { return names; } +// returns: the file the OpenAL library the game plays through was loaded from, in UTF-8, or nothing where that can't +// be told. the game takes OpenAL32.dll from its own folder before the one of the system, so this shows which one it got +std::optional openal_library_path() { +#ifdef _WIN32 + auto *module { ::GetModuleHandleW( L"OpenAL32.dll" ) }; + if( module == nullptr ) { return std::nullopt; } + std::wstring path( 4096, wchar_t{} ); + auto const length { static_cast( ::GetModuleFileNameW( module, path.data(), static_cast( path.size() ) ) ) }; + if( ( length <= 0 ) || ( length >= static_cast( path.size() ) ) ) { return std::nullopt; } + auto const size { ::WideCharToMultiByte( CP_UTF8, 0, path.data(), length, nullptr, 0, nullptr, nullptr ) }; + if( size <= 0 ) { return std::nullopt; } + std::string result( static_cast( size ), char{} ); + ::WideCharToMultiByte( CP_UTF8, 0, path.data(), length, result.data(), size, nullptr, nullptr ); + return result; +#else + return std::nullopt; +#endif +} + } // namespace float const EU07_SOUND_CUTOFFRANGE { 3000.f }; // 2750 m = max expected emitter spawn range, plus safety margin @@ -371,16 +400,151 @@ openal_renderer::~openal_renderer() { if( m_device != nullptr ) { ::alcCloseDevice( m_device ); } } -// invoked by OpenAL (possibly on an internal thread) on device events; only flags the change, -// the actual reopen is done on the main thread in update() +// invoked by OpenAL (possibly on an internal thread) on device events; only notes what happened, +// the device is checked and opened again on the main thread, in follow_output() void ALC_APIENTRY openal_renderer::device_event_callback( ALCenum eventtype, ALCenum devicetype, ALCdevice */*device*/, ALCsizei /*length*/, ALCchar const */*message*/, void *userparam ) noexcept { if( userparam == nullptr ) { return; } if( devicetype == ALC_CAPTURE_DEVICE_SOFT ) { return; } // only care about playback output - if( eventtype != ALC_EVENT_TYPE_DEFAULT_DEVICE_CHANGED_SOFT - && eventtype != ALC_EVENT_TYPE_DEVICE_REMOVED_SOFT ) { return; } - static_cast( userparam )->m_outputchanged.store( true ); + auto event { 0u }; + switch( eventtype ) { + case ALC_EVENT_TYPE_DEFAULT_DEVICE_CHANGED_SOFT: { event = output_follower::default_changed; break; } + case ALC_EVENT_TYPE_DEVICE_REMOVED_SOFT: { event = output_follower::device_removed; break; } + case ALC_EVENT_TYPE_DEVICE_ADDED_SOFT: { event = output_follower::device_added; break; } + default: { return; } + } + static_cast( userparam )->m_outputevents.fetch_or( event ); +} + +// true unless the device is known to have lost its output +bool +openal_renderer::output_connected() const { + + if( false == m_candetectdisconnect ) { return true; } + ALCint connected { ALC_TRUE }; + ::alcGetIntegerv( m_device, ALC_CONNECTED, 1, &connected ); + return connected != ALC_FALSE; +} + +// name of the output the device plays on +std::string +openal_renderer::output_name() const { + + auto const *name { ::alcGetString( m_device, ALC_DEVICE_SPECIFIER ) }; + return name != nullptr ? name : "?"; +} + +// moves the playback to the specified output, null being the default one of the system. the context, the buffers +// and the sources stay as they are. returns true when the device plays on that output afterwards +bool +openal_renderer::reopen_output_on( ALCchar const *Devicename ) { + + auto const reopened { m_alcReopenDeviceSOFT( m_device, Devicename, m_contextattributes.data() ) == ALC_TRUE }; + ::alcGetError( m_device ); // a failure is handled here, don't leave its error code behind + // NOTE: the library reports success also when the new output was opened but failed to start, + // leaving the device disconnected. the result alone can't be trusted + return reopened && output_connected(); +} + +// returns: the name under which the library lists the device set in eu07.ini, or nothing if it isn't listed. the name +// is matched as written and read as code page 1250 text (the starter writes eu07.ini in it), with or without the prefix +// of the library. every attempt to open a device stops the playback for a moment, even one that fails, so a device that +// isn't there isn't tried +std::optional +openal_renderer::find_preferred_output() const { + + if( Global.AudioRenderer.empty() ) { return std::nullopt; } + auto const devices { output_devices() }; + auto const listed = [&devices]( std::string_view const Name ) -> std::optional { + auto const match { std::ranges::find_if( devices, [Name]( std::string_view const Device ) { + return bare_output_name( Device ) == bare_output_name( Name ); } ) }; + if( match == std::end( devices ) ) { return std::nullopt; } + return *match; + }; + if( auto name { listed( Global.AudioRenderer ) } ) { return name; } + if( auto const utf8name { win1250_to_utf8( Global.AudioRenderer ) }; utf8name != Global.AudioRenderer ) { + return listed( utf8name ); + } + return std::nullopt; +} + +// opens the output anew: the device set in eu07.ini if there is one and it works, the default one of the system otherwise +void +openal_renderer::reopen_output( output_follower::clock::time_point const Now ) { + + auto const pinned { false == Global.AudioRenderer.empty() }; + if( pinned ) { + auto name { find_preferred_output() }; + if( false == name.has_value() && false == output_connected() ) { + // not listed under a name that matches, but there is no sound to break anyway: the library may know it still + name = Global.AudioRenderer; + } + if( name.has_value() && reopen_output_on( name->c_str() ) ) { + Global.AudioRenderer = *name; + m_output.succeeded( false, Now ); + WriteLog( std::format( "sound: audio output changed, reopened playback on \"{}\"", output_name() ) ); + return; + } + } + reopen_default_output( pinned, Now ); +} + +// opens the default output of the system. Pinned: it stands in for the device set in eu07.ini +void +openal_renderer::reopen_default_output( bool const Pinned, output_follower::clock::time_point const Now ) { + + if( reopen_output_on( nullptr ) ) { + m_output.succeeded( Pinned, Now ); + WriteLog( std::format( "sound: audio output changed, reopened playback on \"{}\"{}", output_name(), + Pinned ? " (the default output; the device set in eu07.ini isn't available)" : "" ) ); + return; + } + if( m_output.failed( Now ) ) { + // logged once, the following attempts are silent until one works + ErrorLog( "sound: audio output lost and no output could be opened, retrying until one works" ); + } +} + +// while the default output plays in place of the device set in eu07.ini: moves back to that device if it is listed again +void +openal_renderer::restore_preferred_output( output_follower::clock::time_point const Now ) { + + auto const name { find_preferred_output() }; + if( false == name.has_value() ) { + // some other device came, or the one set isn't listed yet: nothing tried, the playback goes on undisturbed + m_output.restore_failed( Now ); + return; + } + if( reopen_output_on( name->c_str() ) ) { + Global.AudioRenderer = *name; + m_output.succeeded( false, Now ); + WriteLog( std::format( "sound: the audio device set in eu07.ini is available again, reopened playback on \"{}\"", output_name() ) ); + return; + } + WriteLog( std::format( "sound: warning: the audio device \"{}\" set in eu07.ini is listed again but doesn't play, staying on the default output", *name ) ); + if( false == output_connected() ) { + // the device opened but didn't start. the library had let go of the default output before it tried, so that's gone too + reopen_default_output( true, Now ); + } + m_output.restore_failed( Now ); +} + +// keeps the sound on an output that works. OpenAL neither moves to another output on its own nor recovers one it lost: +// a device whose output is gone stops all its sources and stays silent, even after the very same output comes back, +// until it is opened again +void +openal_renderer::follow_output() { + + if( m_alcReopenDeviceSOFT == nullptr ) { return; } + + auto const now { output_follower::clock::now() }; + auto const events { m_outputevents.exchange( 0u ) }; + switch( m_output.update( events, now, [this]() { return output_connected(); } ) ) { + case output_follower::action::reopen: { reopen_output( now ); break; } + case output_follower::action::restore_preferred: { restore_preferred_output( now ); break; } + default: { break; } + } } audio::buffer_handle @@ -483,40 +647,8 @@ openal_renderer::update( double const Deltatime ) { if (m_alcDeviceResumeSOFT) m_alcDeviceResumeSOFT(m_device); - // keep audio on the correct output (OpenAL won't re-route on its own). Reopen playback on the - // current default output when the active device is lost (headphones unplugged) or the system - // default output changes (headphones plugged back in, or default switched in Windows). NULL - // device name selects the current default; context and sources are preserved. - if( m_alcReopenDeviceSOFT != nullptr && Global.AudioRenderer.empty() ) { - bool needsreopen{ false }; - if( m_usedeviceevents ) { - // event-driven: the callback (any thread) flags default-output / device-removal changes - needsreopen = m_outputchanged.exchange( false ); - } - if( false == needsreopen && m_candetectdisconnect ) { - // poll for a hard disconnect at ~1 Hz: the fallback without ALC_SOFT_system_events, and a safety net - // with it, as not every backend reports the removal of a device - m_devicechecktime += Deltatime; - if( m_devicechecktime >= 1.0 ) { - m_devicechecktime = 0.0; - ALCint connected{ ALC_TRUE }; - ::alcGetIntegerv( m_device, ALC_CONNECTED, 1, &connected ); - needsreopen = ( connected == ALC_FALSE ); - } - } - if( needsreopen ) { - if( m_alcReopenDeviceSOFT( m_device, nullptr, m_contextattributes.data() ) == ALC_TRUE ) { - auto const *nowon { (char const *)::alcGetString( nullptr, ALC_DEFAULT_ALL_DEVICES_SPECIFIER ) }; - WriteLog( "sound: audio output changed, reopened playback on \"" + std::string{ nowon ? nowon : "?" } + "\"" ); - m_reopenfailed = false; - } - else if( false == m_reopenfailed ) { - // with no output left the poll retries each second; the log gets it once - ErrorLog( "sound: audio output changed but reopening on the default device failed (will retry)" ); - m_reopenfailed = true; - } - } - } + // keep the sound on an output that works + follow_output(); // update listener // gain @@ -686,7 +818,9 @@ openal_renderer::init_caps() { } // NOTE: default value of audio renderer variable is empty string, meaning argument of NULL i.e. 'preferred' device - m_device = open_output_device(); + auto const pinned { false == Global.AudioRenderer.empty() }; + auto fallback { false }; + m_device = open_output_device( fallback ); if( m_device == nullptr ) { ErrorLog( "Failed to obtain audio device" ); return false; @@ -730,9 +864,11 @@ openal_renderer::init_caps() { // the version reported above is the OpenAL API spec level (always 1.1); the real implementation // version string (e.g. "1.1 ALSOFT 1.24.2") is only queryable once a context is current + std::string libraryversion; if( auto const *libversion { (char const *)::alGetString( AL_VERSION ) } ) { crashreport_add_info( "openal_lib_version", libversion ); WriteLog( "sound: library version: " + std::string{ libversion } ); + libraryversion = libversion; } // Initialize all extension function pointers @@ -758,26 +894,53 @@ openal_renderer::init_caps() { if( !m_alcReopenDeviceSOFT ) WriteLog( "sound: warning: extension ALC_SOFT_reopen_device not found; audio output device changes won't be followed" ); - // prefer event-driven output following (ALC_SOFT_system_events) over polling: it reliably - // catches both device removal and default-output changes, incl. re-plugging headphones + // have the system report the changes of the outputs (ALC_SOFT_system_events) where it can. this goes next to + // the periodic check of the connection done by follow_output(), as not every loss of the output is reported if( m_alcReopenDeviceSOFT != nullptr && alcIsExtensionPresent( m_device, "ALC_SOFT_system_events" ) == ALC_TRUE ) { m_alcEventControlSOFT = (LPALCEVENTCONTROLSOFT)alcGetProcAddress( m_device, "alcEventControlSOFT" ); m_alcEventCallbackSOFT = (LPALCEVENTCALLBACKSOFT)alcGetProcAddress( m_device, "alcEventCallbackSOFT" ); if( m_alcEventControlSOFT != nullptr && m_alcEventCallbackSOFT != nullptr ) { m_alcEventCallbackSOFT( &openal_renderer::device_event_callback, this ); - ALCenum const events[]{ ALC_EVENT_TYPE_DEFAULT_DEVICE_CHANGED_SOFT, ALC_EVENT_TYPE_DEVICE_REMOVED_SOFT }; - m_alcEventControlSOFT( 2, events, ALC_TRUE ); + std::array const events { ALC_EVENT_TYPE_DEFAULT_DEVICE_CHANGED_SOFT, ALC_EVENT_TYPE_DEVICE_REMOVED_SOFT, ALC_EVENT_TYPE_DEVICE_ADDED_SOFT }; + m_alcEventControlSOFT( static_cast( events.size() ), events.data(), ALC_TRUE ); m_usedeviceevents = true; WriteLog( "sound: following audio output device changes via ALC_SOFT_system_events" ); } } + if( m_alcReopenDeviceSOFT != nullptr && false == m_usedeviceevents ) { + WriteLog( "sound: warning: extension ALC_SOFT_system_events not found; a lost audio output is recovered, a change of the default one and the return of the device set in eu07.ini aren't followed" ); + } + m_output.start( pinned, fallback, output_follower::clock::now() ); + log_output_following( libraryversion, pinned ); init_extensions(); return true; } +// says in one line which OpenAL library the game got and whether the sound follows the output device with it. an old +// library (OpenAL Soft before 1.23, as the one the game came with) is left as it is: the sound plays on the device opened +// at the start, as it always did, and only the log says why it doesn't move +void +openal_renderer::log_output_following( std::string_view const Version, bool const Pinned ) const { + + auto const library { openal_library_path() }; + auto const name { std::format( "\"{}\"{}", Version.empty() ? std::string_view{ "unknown" } : Version, + library.has_value() ? std::format( " from \"{}\"", *library ) : std::string{} ) }; + if( ( m_alcReopenDeviceSOFT == nullptr ) || ( false == m_usedeviceevents ) ) { + WriteLog( std::format( "sound: warning: the OpenAL library {} is too old to follow a change of the audio output; " + "the sound stays on the device opened at the start. OpenAL Soft 1.23 or newer, as OpenAL32.dll in the game folder, follows it", name ) ); + return; + } + if( Pinned ) { + WriteLog( std::format( "sound: the OpenAL library {} follows the audio output: the device set in eu07.ini (sound.openal.renderer), " + "the default output of the system while that one isn't there", name ) ); + return; + } + WriteLog( std::format( "sound: the OpenAL library {} follows the audio output: the default output of the system", name ) ); +} + // resolves the entry points of the context extensions the settings use: source resampler, EFX filters void openal_renderer::init_extensions() { @@ -978,8 +1141,22 @@ openal_renderer::apply_device_settings() { m_contextattributes = device_attributes(); auto applied { false }; if( m_alcReopenDeviceSOFT != nullptr ) { - auto const *devicename { Global.AudioRenderer.empty() ? nullptr : Global.AudioRenderer.c_str() }; - applied = ( m_alcReopenDeviceSOFT( m_device, devicename, m_contextattributes.data() ) == ALC_TRUE ); + auto const pinned { false == Global.AudioRenderer.empty() }; + if( pinned ) { + // the playback is opened anew here anyway, so a name the list doesn't match is tried too + auto const name { find_preferred_output().value_or( Global.AudioRenderer ) }; + applied = reopen_output_on( name.c_str() ); + if( applied ) { Global.AudioRenderer = name; } + } + auto const fallback { pinned && false == applied }; + if( false == applied ) { + // no device set, or the one set isn't there: the default one, which follow_output() leaves once the other is back + applied = reopen_output_on( nullptr ); + } + if( applied ) { + // the device may have been changed in the settings: the output is followed by what is set now + m_output.start( pinned, fallback, output_follower::clock::now() ); + } } else if( m_alcResetDeviceSOFT != nullptr ) { // without ALC_SOFT_reopen_device another output device takes a restart diff --git a/audio/audiorenderer.h b/audio/audiorenderer.h index f6e247104..afa73ee93 100644 --- a/audio/audiorenderer.h +++ b/audio/audiorenderer.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include "audio/audio.h" +#include "audio/outputfollow.h" #include "audio/fmradio.h" #include "audio/startsample.h" #include "model/ResourceManager.h" @@ -20,6 +21,8 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include +#include // Definicje dla OpenAL 1.25 jeśli brakuje #ifndef ALC_CONNECTED @@ -151,10 +154,20 @@ private: bool init_caps(); void init_extensions(); + void log_output_following( std::string_view Version, bool Pinned ) const; std::vector device_attributes() const; int hrtf_index( std::string const &Name ) const; ALint resampler_index() const; void configure_source( ALuint const Source ) const; + // keeps the sound on an output that works, see audio::output_follower + void follow_output(); + void reopen_output( output_follower::clock::time_point const Now ); + void restore_preferred_output( output_follower::clock::time_point const Now ); + void reopen_default_output( bool const Pinned, output_follower::clock::time_point const Now ); + std::optional find_preferred_output() const; + bool reopen_output_on( ALCchar const *Devicename ); + bool output_connected() const; + std::string output_name() const; audio::openal_source fetch_source(); ALCdevice *m_device { nullptr }; @@ -192,16 +205,15 @@ private: bool m_candetectdisconnect { false }; std::vector m_contextattributes; // cached for device reopen - double m_devicechecktime { 0.0 }; - bool m_reopenfailed { false }; // a failed reopen is retried each second, but logged once + output_follower m_output; // decides when the device is opened again - // ALC_SOFT_system_events: event-driven following of output-device / default-output changes. - // Preferred over polling because it reliably catches both device removal and default changes - // (e.g. re-plugging headphones), which alcGetString(DEFAULT_ALL_DEVICES) does not report live. + // ALC_SOFT_system_events: the system reports output devices coming, going and the default one changing. + // Used next to the periodic check of the connection, not in place of it: the events catch a change of the + // default output at once (e.g. re-plugging headphones), the check catches the losses the system doesn't report. LPALCEVENTCONTROLSOFT m_alcEventControlSOFT { nullptr }; LPALCEVENTCALLBACKSOFT m_alcEventCallbackSOFT { nullptr }; bool m_usedeviceevents { false }; - std::atomic m_outputchanged { false }; // set from the (possibly off-thread) event callback + std::atomic m_outputevents { 0u }; // bits of output_follower::event, set from the (possibly off-thread) event callback static void ALC_APIENTRY device_event_callback( ALCenum eventtype, ALCenum devicetype, ALCdevice *device, ALCsizei length, ALCchar const *message, void *userparam ) noexcept; }; diff --git a/audio/outputfollow.h b/audio/outputfollow.h new file mode 100644 index 000000000..46d36dff7 --- /dev/null +++ b/audio/outputfollow.h @@ -0,0 +1,154 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include + +namespace audio { + +// decides when the playback device has to be opened again, so the sound follows the output of the system: +// headphones pulled out or plugged in, another default output chosen, the device taken away and given back. +// holds no OpenAL state of its own: the renderer feeds it the events of the system and the state of the device, +// and does what it answers. kept apart from the renderer so the unit tests can run it +class output_follower { + +public: + using clock = std::chrono::steady_clock; + + // what the system reported since the last update, combined as bits + enum event : unsigned { + default_changed = 1u << 0, // another output became the default one + device_removed = 1u << 1, // an output is gone, possibly the one in use + device_added = 1u << 2 // an output appeared, possibly the one set in eu07.ini + }; + + enum class action { + none, + reopen, // open the output anew: the one set in eu07.ini if there is one and it works, the default one otherwise + restore_preferred // playing on the default output in place of the one set in eu07.ini: see whether that one is back + }; + + // how often a working device is asked whether it is still connected. the system doesn't report every loss of the + // output (a stream invalidated without the device being removed), so the events alone leave the game silent + static constexpr std::chrono::milliseconds check_interval { 1000 }; + // delays between the attempts to open an output while there is none that works. every attempt runs on the main + // thread and may take tens of milliseconds, so after the first minute without an output they thin out + static constexpr std::chrono::milliseconds retry_min { 500 }; + static constexpr std::chrono::milliseconds retry_max { 4000 }; + static constexpr std::chrono::milliseconds retry_late_after { 60000 }; + static constexpr std::chrono::milliseconds retry_late { 30000 }; + // while there is no output an event of the system has the next attempt made at once, but not sooner than this after + // the last one: a device coming (a bluetooth headset, say) reports a burst of events over a few frames + static constexpr std::chrono::milliseconds event_retry_min { 250 }; + // the device set in eu07.ini can be reported before it is ready to play. a move back to it that didn't work out is + // tried again after 1, 2 and 4 s; then the next arrival of a device is waited for, so a device that never works + // (taken in exclusive mode by another program, say) doesn't break the sound every few seconds + static constexpr std::chrono::milliseconds restore_retry_min { 1000 }; + static constexpr int restore_retries { 3 }; + + // Pinned: a device is set in eu07.ini (sound.openal.renderer); Fallback: it couldn't be opened and the default one plays instead + void + start( bool const Pinned, bool const Fallback, clock::time_point const Now ) { + m_pinned = Pinned; + m_fallback = Pinned && Fallback; + m_lost = false; + m_retrydelay = retry_min; + m_nextcheck = Now + check_interval; + m_restorefailures = 0; + } + + // Events: bits of event; Connected: callable telling whether the device still works, called only when a check is due + template + action + update( unsigned const Events, clock::time_point const Now, Probe_ const &Connected ) { + if( m_lost ) { + // no working output: whatever the system reports may be the output coming back, so it brings the next attempt + // forward. otherwise it comes after a growing delay + if( Events != 0u ) { m_nextcheck = std::min( m_nextcheck, m_lastattempt + event_retry_min ); } + return ( Now >= m_nextcheck ) ? action::reopen : action::none; + } + if( ( Now >= m_nextcheck ) || ( ( Events & device_removed ) != 0u ) ) { + m_nextcheck = Now + check_interval; + if( false == Connected() ) { return action::reopen; } + } + if( follows_default() && ( ( Events & default_changed ) != 0u ) ) { return action::reopen; } + if( m_fallback ) { + if( ( Events & device_added ) != 0u ) { + // a device that appears may be the one set: a fresh round of attempts + m_restorefailures = 0; + return action::restore_preferred; + } + if( ( m_restorefailures > 0 ) && ( m_restorefailures <= restore_retries ) && ( Now >= m_nextrestore ) ) { + return action::restore_preferred; + } + } + return action::none; + } + + // an output was opened and works. Fallback: it is the default one, in place of the one set in eu07.ini + void + succeeded( bool const Fallback, clock::time_point const Now ) { + m_fallback = m_pinned && Fallback; + m_lost = false; + m_retrydelay = retry_min; + m_nextcheck = Now + check_interval; + // the default output standing in again doesn't end the round of attempts to move back to the device set + if( false == m_fallback ) { m_restorefailures = 0; } + } + + // no output could be opened. returns true for the first failure in a row, the one worth a line in the log + bool + failed( clock::time_point const Now ) { + auto const first { false == m_lost }; + if( first ) { + m_loststart = Now; + m_retrydelay = retry_min; + } + else if( Now - m_loststart >= retry_late_after ) { + m_retrydelay = retry_late; + } + else { + m_retrydelay = std::min( m_retrydelay * 2, retry_max ); + } + m_lost = true; + m_lastattempt = Now; + m_nextcheck = Now + m_retrydelay; + return first; + } + + // the move back to the device set in eu07.ini didn't work out: the device isn't listed, or it didn't open or start. + // schedules the next attempt of the round, if there is one left + void + restore_failed( clock::time_point const Now ) { + ++m_restorefailures; + if( m_restorefailures <= restore_retries ) { + m_nextrestore = Now + restore_retry_min * ( 1 << ( m_restorefailures - 1 ) ); + } + } + + bool lost() const { return m_lost; } + bool fallback() const { return m_fallback; } + // a device set in eu07.ini is left alone for as long as it works; otherwise the sound goes where the system sends it + bool follows_default() const { return false == m_pinned || m_fallback; } + +private: + bool m_pinned { false }; + bool m_fallback { false }; + bool m_lost { false }; // the output is gone and none could be opened so far + std::chrono::milliseconds m_retrydelay { retry_min }; + clock::time_point m_nextcheck {}; // of the connection while the output works, the next attempt to open one while it doesn't + clock::time_point m_loststart {}; // the first failed attempt of the current loss + clock::time_point m_lastattempt {}; // the last failed attempt, while the output is lost + int m_restorefailures { 0 }; // failed moves back to the device set since it last appeared, 0 when none is due + clock::time_point m_nextrestore {}; +}; + +} // namespace audio diff --git a/tests/unit/test_audio_output.cpp b/tests/unit/test_audio_output.cpp new file mode 100644 index 000000000..a2319b960 --- /dev/null +++ b/tests/unit/test_audio_output.cpp @@ -0,0 +1,259 @@ +#include "stdafx.h" + +#include "doctest.h" + +#include "audio/outputfollow.h" + +// the following of the audio output: when the renderer is told to open its playback device again + +namespace +{ + +using audio::output_follower; +using action = audio::output_follower::action; +using std::chrono::milliseconds; + +// a follower with a device that answers the checks of its connection as told, and counts them +struct output_rig +{ + output_follower follower; + output_follower::clock::time_point now{}; + bool connected{true}; + int checks{0}; + + explicit output_rig(bool const Pinned = false, bool const Fallback = false) + { + follower.start(Pinned, Fallback, now); + } + action step(milliseconds const Elapsed, unsigned const Events = 0u) + { + now += Elapsed; + return follower.update(Events, now, [this]() { + ++checks; + return connected; + }); + } +}; + +} // namespace + +TEST_CASE("audio output: a working device is left alone and checked about once a second") +{ + output_rig rig; + for (int frame = 0; frame < 300; ++frame) // 3 s at 100 fps + CHECK(rig.step(milliseconds{10}) == action::none); + CHECK(rig.checks == 3); +} + +TEST_CASE("audio output: a lost connection is found without any event from the system") +{ + // the stream invalidated, the device not removed and the default output unchanged: nothing is reported + output_rig rig; + rig.connected = false; + CHECK(rig.step(milliseconds{500}) == action::none); // not yet checked + CHECK(rig.step(milliseconds{500}) == action::reopen); + CHECK(rig.checks == 1); +} + +TEST_CASE("audio output: a removed device has the connection checked at once") +{ + output_rig rig; + CHECK(rig.step(milliseconds{10}, output_follower::device_removed) == action::none); // another device was removed + CHECK(rig.checks == 1); + rig.connected = false; + CHECK(rig.step(milliseconds{10}, output_follower::device_removed) == action::reopen); +} + +TEST_CASE("audio output: a change of the default output is followed, the arrival of some device is not") +{ + output_rig rig; + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::none); + CHECK(rig.step(milliseconds{10}, output_follower::default_changed) == action::reopen); + CHECK(rig.checks == 0); +} + +TEST_CASE("audio output: opening that failed is tried again, with growing delays and at once on any event") +{ + output_rig rig; + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); + CHECK(rig.follower.failed(rig.now)); // the first failure in a row is the one to log + CHECK(rig.follower.lost()); + + // the following attempts come after 0.5, 1, 2, 4 and then every 4 s + for (auto const delay : {500, 1000, 2000, 4000, 4000}) + { + CHECK(rig.step(milliseconds{delay - 1}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::reopen); + CHECK_FALSE(rig.follower.failed(rig.now)); + } + // whatever the system reports may be the output coming back: the next attempt at once, but not sooner than + // event_retry_min after the last one, as a device coming reports a burst of events + CHECK(rig.step(milliseconds{1}, output_follower::device_added) == action::none); + CHECK(rig.step(output_follower::event_retry_min - milliseconds{2}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::reopen); // the event brought the attempt forward and wasn't forgotten + CHECK_FALSE(rig.follower.failed(rig.now)); + CHECK(rig.step(output_follower::event_retry_min, output_follower::default_changed) == action::reopen); + + // a lost device isn't asked about its connection, it is opened again + CHECK(rig.checks == 1); + + rig.connected = true; + rig.follower.succeeded(false, rig.now); + CHECK_FALSE(rig.follower.lost()); + CHECK(rig.step(milliseconds{10}) == action::none); + // and the next loss starts from the short delay, with its own line in the log + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); + CHECK(rig.follower.failed(rig.now)); + CHECK(rig.step(output_follower::retry_min) == action::reopen); +} + +TEST_CASE("audio output: a device set in eu07.ini doesn't follow the default output while it works") +{ + output_rig rig{true}; + CHECK_FALSE(rig.follower.follows_default()); + CHECK(rig.step(milliseconds{10}, output_follower::default_changed) == action::none); + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::none); + // but it is opened again when it loses the connection + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); +} + +TEST_CASE("audio output: the default output standing in for the device set in eu07.ini") +{ + output_rig rig{true}; + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); + // the device set is gone, the default one was opened instead + rig.connected = true; + rig.follower.succeeded(true, rig.now); + CHECK(rig.follower.fallback()); + CHECK(rig.follower.follows_default()); + + // the default output is followed for as long as it stands in + CHECK(rig.step(milliseconds{10}, output_follower::default_changed) == action::reopen); + rig.follower.succeeded(true, rig.now); + // and a device that appears may be the one set + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + CHECK(rig.follower.fallback()); // it wasn't, nothing changes + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + rig.follower.succeeded(false, rig.now); + CHECK_FALSE(rig.follower.fallback()); + CHECK(rig.step(milliseconds{10}, output_follower::default_changed) == action::none); +} + +TEST_CASE("audio output: the game started on the default output, the device set in eu07.ini being absent") +{ + output_rig rig{true, true}; + CHECK(rig.follower.fallback()); + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); +} + +TEST_CASE("audio output: without a device set in eu07.ini there is nothing to fall back from") +{ + output_rig rig{false, true}; + CHECK_FALSE(rig.follower.fallback()); + rig.follower.succeeded(true, rig.now); + CHECK_FALSE(rig.follower.fallback()); + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::none); +} + +TEST_CASE("audio output: after a minute without an output the attempts thin out, the events still count at once") +{ + output_rig rig; + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); + CHECK(rig.follower.failed(rig.now)); + auto const loststart{rig.now}; + + // 0.5, 1, 2, then 4 s until a minute has gone by since the first failure + while (rig.now - loststart < output_follower::retry_late_after) + { + auto const before{rig.now}; + auto next{rig.step(milliseconds{50})}; + while (next != action::reopen) + next = rig.step(milliseconds{50}); + CHECK(rig.now - before <= output_follower::retry_max); + rig.follower.failed(rig.now); + } + // the failure past the minute puts the next attempt 30 s away + CHECK(rig.step(output_follower::retry_late - milliseconds{1}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::reopen); + rig.follower.failed(rig.now); + CHECK(rig.step(output_follower::retry_late - milliseconds{1}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::reopen); + rig.follower.failed(rig.now); + + // a device coming has the attempt made at once still + CHECK(rig.step(output_follower::event_retry_min, output_follower::device_added) == action::reopen); + rig.follower.failed(rig.now); + + // and the next loss starts from the short delays again + rig.follower.succeeded(false, rig.now); + CHECK(rig.step(output_follower::check_interval) == action::reopen); + CHECK(rig.follower.failed(rig.now)); + CHECK(rig.step(output_follower::retry_min) == action::reopen); +} + +TEST_CASE("audio output: a move back to the device set in eu07.ini that didn't work out is tried again 3 times") +{ + output_rig rig{true, true}; + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + rig.follower.restore_failed(rig.now); // reported before it was ready, say + + // again after 1, 2 and 4 s + for (auto const delay : {1000, 2000, 4000}) + { + CHECK(rig.step(milliseconds{delay - 1}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::restore_preferred); + rig.follower.restore_failed(rig.now); + } + // then not any more: a device that never works doesn't break the sound every few seconds + for (int second = 0; second < 60; ++second) + CHECK(rig.step(milliseconds{1000}) == action::none); + + // until a device appears again, which starts a fresh round + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + rig.follower.restore_failed(rig.now); + CHECK(rig.step(output_follower::restore_retry_min) == action::restore_preferred); + + // the device works this time: nothing more to try + rig.follower.succeeded(false, rig.now); + CHECK_FALSE(rig.follower.fallback()); + for (int second = 0; second < 10; ++second) + CHECK(rig.step(milliseconds{1000}) == action::none); +} + +TEST_CASE("audio output: the default output opened anew after a failed move back keeps the round of attempts") +{ + // the device set opened but didn't start, and the library had let go of the default output before: that's opened + // again, and the move back is still retried, with no endless round + output_rig rig{true, true}; + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + for (int attempt = 0; attempt < output_follower::restore_retries; ++attempt) + { + rig.follower.succeeded(true, rig.now); + rig.follower.restore_failed(rig.now); + CHECK(rig.follower.fallback()); + action next{action::none}; + for (int frame = 0; frame < 1000 && next == action::none; ++frame) + next = rig.step(milliseconds{10}); + CHECK(next == action::restore_preferred); + } + rig.follower.succeeded(true, rig.now); + rig.follower.restore_failed(rig.now); + for (int second = 0; second < 60; ++second) + CHECK(rig.step(milliseconds{1000}) == action::none); +} + +TEST_CASE("audio output: the settings applied drop a pending move back") +{ + output_rig rig{true, true}; + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + rig.follower.restore_failed(rig.now); + // the settings applied: the device set may be another one now, a pending attempt is dropped + rig.follower.start(true, true, rig.now); + for (int second = 0; second < 10; ++second) + CHECK(rig.step(milliseconds{1000}) == action::none); +}