18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-11-27 21:45:16 +01:00
Files
maszyna/simulation/simulationtest.cpp
jerrrrycho 3eb2fdf462 Merge staging into feat/gl46-migration
origin/staging 7ac2472c3 into feat/gl46-migration db26a33ed, so that #468
merges into staging. Merge base 037158104. Staging carries master up to
571487612 (squashed in #514); this branch had merged master up to 7c12b83ba.

Conflicts, file by file:
- README.md: WITH_BETTER_RENDERER row dropped (gl46), USE_SYSTEM_JSON row kept (staging)
- CMakeLists.txt: gl46 lists, plus staging's new core sources (hardwareinfo, sn_utils, regionfile, inionlysettings, fieldshunting, gaugewrap, drivingaid, signalpassing, brakereleaser, crew, brakecharge); none listed twice
- tests/unit/CMakeLists.txt: both (texturealpha, freecameramotion; editorSwitchDrives, Camera)
- vehicle/brakingcurve.{h,cpp}, tests/unit/test_braking_curve.cpp (add/add): staging (#479 brake_acting on the same #409 code)
- editor/editorHttp.cpp: staging (it has gl46's #432 and certificate fixes, plus #439 libcurl loaded at run time)
- tests/unit/test_editor_http.cpp (add/add): staging (adds the available() case of #439)
- utilities/Globals.h: gl46 crashdump_full (staging's CrashDumpFull is #425, replaced here by utilities/crashdump.cpp); fmradio and staging's OpenAL options both; gfx_headlights_beamwidth (#481) not taken
- utilities/Globals.cpp: both (odometer.expiry, OpenAL keys, fmradio, gl46 gfx keys); gfx.headlights.beamwidth (#481) not taken
- utilities/Logs.cpp: staging's log_file_name() for both files, with gl46's crashdump_set_log_file() for both
- utilities/utilities.h: gl46 set_thread_random_engine(); Random(int, int) gone on both sides
- tests/unit/test_utilities.cpp: staging's includes
- simulation/simulationtest.cpp: gl46 (no NvRenderer, LegacyRenderer, BasicRenderer here)
- ci_shadervalidator/* (incl. add/add utilities/Logs.h): gl46's validator of shaders/ogl46 and shaders/vk14; staging's #437 fixed the GL 3.3 one
- gl/shader.cpp, gl/glsl_common.cpp: gl46 (shaders come from rendering/common/shadersource.cpp); HEADLIGHT_BEAM_WIDTH (#481) not taken
- shaders/mat_wire.frag: gl46. Rename detection paired staging's mat_colored.frag (#481) with it
- lang/editor_pl.po: union; the 12 camera speed / orthophoto entries staging adds are here already (master #312)
- audio/audiorenderer.{h,cpp}: both (fmradio; startsample and the low-pass filter); the destructor releases the radio, then the filter
- application/editormode.h, application/editormodeswitchdrive.cpp: staging (#509 on #330, which is all this side had)
- application/application.cpp: gl46's start sequence (no init_ogl, ANGLE or NvRenderer; crash window after init_ui) with staging's hardware::log_system() (#389)
- EU07.cpp: gl46 (crash reports of utilities/crashdump.cpp); staging's side was #425's handler, replaced here
- model/Texture.{h,cpp}: gl46 (texture_source); staging's side is master #399/#411/#362/#386, merged here before
- world/Track.h, world/TrackSleepers.h: both (TrackBlend, lay(Fastened)/fasten; TrackBuckle, pack_models)
- world/Segment.cpp: staging's track buckling on the split stray factors both sides have
- vehicle/Driver.h: staging's additions (#444, #494, #473, #346, timetable flags)
- vehicle/Driver.cpp: staging's file, with this branch's f4f8c75e4 (road orders measured along the lane) and 8fbf05674 (a holding road order blocks the ones past it) applied again; #409's SeenAheadTolerance gives way to #473
- vehicle/DynObj.h: friend opengl46_renderer and friend class vehicle_table
- vehicle/DynObj.cpp: gl46's vehicle_table::update() with staging's update_off_track_contacts() and update_brake_pipes()
- McZapkie/Mover.cpp: staging's function splits (#239) and hose exchange (#388); every line this branch added to Mover.cpp/MOVER.h is kept
- .github/workflows/build_bin.yml: staging's apt-install step (#497) and pinned download-artifact (#331)

Modify/delete, kept deleted:
- rendering/opengl33renderer.{cpp,h}, rendering/openglparticles.cpp, rendering/openglrenderer.{cpp,h}: staging's versions are master's, and every master change to them is in this branch's history already
- shaders/light_common.glsl, shaders/mat_sunlessnormalmap_specgloss.frag: see below

Carried into this branch's code:
- the hose exchange after each sub-step (#387/#388) also in update_steps_parallel(), per group of vehicles, as update() does it single-threaded
- physics.pipewake (pipe_wakes(), wake_cause::scndpipe) in staging's GetScndDVc(), where the main reservoir hose exchange went
- hardware::log_gl_context() (#389) in after_window() of the GL 4.6 backend, init_ogl() being gone

Taken back out of the auto-merge (renderers this branch removed):
- shaders/vk14/tonemapping.glsl: #481's switch to ACES, applied there by rename detection
- environment/skydome.cpp, simulation/simulationenvironment.cpp: #415, the sky of the legacy renderer
- application/application.cpp: #384's fallback of an unknown gfxrenderer, which this branch had dropped

Not carried from staging (renderer files removed here):
- master #481 (571487612): old assets drawn as in 26.05 (metal diffuse, sun highlight tint, ACES, SUN_DIFFUSE_SCALE 2.5, untinted Diffuse, mat_colored base) and gfx.headlights.beamwidth. Made for the GL 3.3 shaders; the PBR shaders of shaders/ogl46 and vk14 (and their SPIR-V binaries) are the author's call
- #437: the unique temporary file of the shader validator (Sonar S5443); gl46's validator still writes /tmp/shader*

Unit tests: 1133 of 1137 cases pass. Four staging tests fail (derailment: a
repaired vehicle is back on the rails; three pullee cases): the vehicle
stands, and with physics.sleepheld (on by default here) its physics sleeps
with the Fb / FStand of before. With physics.sleepheld off they pass. Left
to the author.
2026-11-27 05:26:13 +01:00

274 lines
8.9 KiB
C++

/*
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 "simulation/simulationtest.h"
#include "application/application.h"
#include "scene/scene.h"
#include "simulation/simulation.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/physicslog.h"
#include "utilities/utilities.h"
#include "vehicle/DynObj.h"
#include "world/Event.h"
#include "world/MemCell.h"
#ifdef _WIN32
#include "Console.h"
#endif
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <format>
#include <memory>
namespace {
bool is_moving(TDynamicObject const *Vehicle)
{
return std::abs(Vehicle->GetVelocity()) > 0.01;
}
// [s] of real time since the start of the simulator
double elapsed_wall_time()
{
return std::chrono::duration<double>(std::chrono::steady_clock::now() - Global.startTimestamp).count();
}
} // namespace
namespace simulation {
test_manager &test()
{
static test_manager instance;
return instance;
}
void apply_test_mode_settings()
{
// nobody watches nor listens: no player vehicle, nothing drawn, no sound, no window in the way
Global.editor_session = false;
Global.local_start_vehicle = "ghostview";
Global.GfxRenderer = "null";
Global.bSoundEnabled = false;
Global.python_enabled = false;
Global.bInactivePause = false;
Global.bFullScreen = false;
Global.fullscreen_windowed = false;
Global.VSync = false;
Global.iMultisampling = 0;
Global.minframetime = std::chrono::duration<float>(0.0f);
Global.extra_viewports.clear();
Global.headtrack_conf.joy.clear();
// a test runs on its own: no network, and no input from outside (eu07/maszyna#541)
Global.network_servers.clear();
Global.network_client.reset();
Global.InputGamepad = false;
Global.InputMouse = false;
Global.uart_conf.enable = false;
Global.motiontelemetry_conf.enable = false;
#ifdef WITH_ZMQ
Global.zmq_address.clear();
#endif
// nor anything to the outside: no keyboard leds, LPT or PoKeys desk (feedbackmode), no messages to a
// multiplayer server (multiplayer, which also holds some events back for it), no program run at the end
Global.iFeedbackMode = 0;
#ifdef _WIN32
Console::ModeSet(Global.iFeedbackMode, Global.iFeedbackPort);
#endif
Global.iMultiplayer = 0;
Global.exec_on_exit.clear();
// and the same way every time, unless given another seed (-seed, or randomseed in the settings)
if (false == Global.random_seed_given) {
Global.random_seed = seed_of("test");
Global.random_seed_given = true;
}
// the real time limit, which the scenery may set too
test().watch_wall_clock(wall_clock_limit(Global.test.wall_timeout, Global.test.timeout));
}
void test_manager::init_result_cell() const
{
auto cell { std::make_unique<TMemCell>(scene::node_data{0, -1, std::string(result_cell), "memcell"}) };
// neither of the reported values, so that a cell nobody wrote to says nothing
cell->UpdateValues("", -1.0, 0.0, basic_event::flags::value1 | basic_event::flags::value2);
simulation::Region->insert(cell.get());
// the table owns its cells
simulation::Memory.insert(cell.release());
}
void test_manager::start()
{
if (m_started)
return;
m_started = true;
{
std::scoped_lock lock { m_lock };
m_progress = test_progress {};
}
if (simulation::Vehicles.sequence().empty())
{
// most likely the scenery wasn't found, or it isn't a test scenery
finish(test_result::error, "the scenery has no vehicles");
return;
}
for (auto const &name : Global.test.vehicles)
{
if (simulation::Vehicles.find(name) == nullptr)
{
finish(test_result::error, std::format("the scenery has no vehicle {} (test.vehicle)", name));
return;
}
}
// a pause set by the scenery or the settings would never be lifted, nobody is there to press the key
Global.iPause = 0;
auto tested { std::string("every vehicle") };
if (false == Global.test.vehicles.empty())
{
tested = "the consists of";
for (auto const &name : Global.test.vehicles)
tested += " " + name;
}
auto const walllimit { m_walllimit.load() };
WriteLog(std::format("test: started, testing {}, timeout {:.0f} s, real time limit {}, standstill {:.0f} s{}{}{}", tested, Global.test.timeout,
walllimit > 0.0 ? std::format("{:.0f} s", walllimit) : std::string("none"), Global.test.standstill,
Global.test.pass_on_standstill ? ", standstill passes" : "",
Global.test.fail_if_stop_overran ? "" : ", signals passed at danger allowed",
Global.test.no_movement_before_pass ? "" : ", pass without waiting for a stop"));
}
void test_manager::update(double const Deltatime)
{
if (false == m_started || m_finished)
return;
test_frame frame { Deltatime, std::nullopt, {}, tested_trains_at_rest() };
if (auto const *cell = simulation::Memory.find(std::string(result_cell)))
{
frame.reported = cell->Value1();
frame.reason = cell->Text();
}
auto const limits { test_limits { Global.test.timeout, Global.test.standstill, Global.test.pass_on_standstill, Global.test.no_movement_before_pass } };
std::optional<test_verdict> verdict;
auto passrequested { false };
{
std::scoped_lock lock { m_lock };
auto const requestedbefore { m_progress.passrequested };
verdict = evaluate_frame(m_progress, frame, limits);
passrequested = m_progress.passrequested && false == requestedbefore;
}
if (verdict.has_value())
{
finish(verdict->result, verdict->reason);
return;
}
if (passrequested)
{
WriteLog(std::format("test: pass requested at {:.1f} s{}, waiting for the tested trains to stop", m_progress.time,
frame.reason.empty() ? std::string() : std::format(" ({})", frame.reason)));
}
}
bool test_manager::tested_trains_at_rest() const
{
if (Global.test.vehicles.empty())
return std::ranges::none_of(simulation::Vehicles.sequence(), is_moving);
// the consists as they are now: a train the tested one couples to joins it, one it leaves behind doesn't
return std::ranges::none_of(Global.test.vehicles, [](std::string const &Name) {
auto *vehicle { simulation::Vehicles.find(Name) };
return vehicle != nullptr && vehicle->find_vehicle(coupling::coupler, is_moving) != nullptr;
});
}
void test_manager::signal_passed_at_danger(std::string_view const Vehicle, std::string_view const Signal)
{
auto const reason { std::format("{} passed signal {} at danger", Vehicle, Signal) };
if (false == Global.test.enabled)
{
WriteLog(reason, logtype::generic);
return;
}
if (false == Global.test.fail_if_stop_overran)
{
WriteLog(std::format("test: {} at {:.1f} s, allowed by test.fail_if_stop_overran", reason, m_progress.time));
return;
}
finish(test_result::signal_passed_at_danger, reason);
}
void test_manager::finish(test_result const Result, std::string_view const Reason)
{
if (conclude(Result, Reason))
Application.queue_quit(true);
}
bool test_manager::conclude(test_result const Result, std::string_view const Reason)
{
std::scoped_lock lock { m_lock };
if (m_finished || false == Global.test.enabled)
return false;
m_result = Result;
m_finished = true;
auto const line { std::format("test: {} (exit code {}) after {:.1f} s of simulation time: {}", to_string(Result), static_cast<int>(Result), m_progress.time, Reason) };
if (Result == test_result::pass)
WriteLog(line);
else
ErrorLog(line);
// the process has no console of its own; whoever started it with a redirected output gets the verdict there too
std::fprintf(stdout, "%s\n", line.c_str());
std::fflush(stdout);
return true;
}
int test_manager::exit_code() const
{
std::scoped_lock lock { m_lock };
return static_cast<int>(m_finished ? m_result : test_result::error);
}
void test_manager::watch_wall_clock(double const Limit)
{
m_walllimit = Limit;
if (Limit <= 0.0 || m_watchdog.joinable())
return;
m_watchdog = std::jthread([this](std::stop_token const &Stop) {
while (false == Stop.stop_requested())
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
check_wall_clock(elapsed_wall_time());
}
});
}
void test_manager::check_wall_clock(double const Elapsed)
{
auto const limit { m_walllimit.load() };
if (limit <= 0.0 || Elapsed < limit)
return;
// the run hangs, or is too slow: it ends here, whatever the main thread is doing. a run whose test has ended
// but which doesn't close ends with its result
if (false == conclude(test_result::timeout, std::format("still running after {:.0f} s of real time (test.wall_timeout)", limit)))
ErrorLog(std::format("test: the simulator was still running {:.0f} s of real time after the start, ended", limit));
// what was logged last gets written, unless the log is held up by a hung thread, or the physics logs by a writer
// holding their files or a disk which doesn't answer: the run ends anyway, two seconds later at most
PhysicsLogs.flush_for(std::chrono::seconds{2});
StopLogService();
std::this_thread::sleep_for(std::chrono::milliseconds(250));
std::_Exit(exit_code());
}
} // namespace simulation