From 1996301a7ba6eff42691be31546ead334af5b1c4 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 03:35:29 +0100 Subject: [PATCH 01/17] perf(physics): the MED log is tried once per vehicle when it can't be opened A vehicle blending ED and EP brakes (ConsistBrakeBlending) opens MEDLOGS/_.csv once it brakes while moving. Without the MEDLOGS folder, which the game doesn't come with, the open failed and was tried again on every step of the braking: a path built and a CreateFile call each time, with counted up. The failure is now remembered and the log isn't tried again for that vehicle. With the folder there the first attempt opens it, and what is written is the same as before. Tomaszewo (raj40821) 600 s in --test, seed 12345: OpenLog was 0.18% of the main thread there (few ED consists brake in it), the run time is within noise (sim 268.3 s median of 3 before, 269.8 s after); the 14 physics logs and the event log are byte-identical, unit tests 1205/1205 with exact golden traces. --- physics/consistbraking.cpp | 8 +++++++- physics/consistbraking.h | 1 + 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/physics/consistbraking.cpp b/physics/consistbraking.cpp index 2f86603cb..4e68f932f 100644 --- a/physics/consistbraking.cpp +++ b/physics/consistbraking.cpp @@ -193,11 +193,17 @@ void physics::ConsistBrakeBlending::ComputeDemand(Step &state, Vehicle &Lead, do // the log of the braking of the consist opened, once it brakes while moving void physics::ConsistBrakeBlending::OpenLog(Step const &state, Vehicle const &Lead) { - if (state.Fzad > 1 && !log.is_open() && Lead.Vel > 1) + if (state.Fzad > 1 && !log.is_open() && false == logUnavailable && Lead.Vel > 1) { log.open( "MEDLOGS/" + Lead.Name + "_" + std::to_string( ++logCount ) + ".csv", std::ios::in | std::ios::out | std::ios::trunc ); + if( false == log.is_open() ) { + // no MEDLOGS folder (the usual case, the game doesn't come with one): not tried again for this vehicle. + // an attempt costs a file system call, and it used to be made on every step of the braking + logUnavailable = true; + return; + } log << "t\tVel\tMasa\tOsie\tFmaxPN\tFmaxED\tFfulED\tFrED\tFzad\tFzadED\tFzadPN"; for(int k=1;k<=state.np;k++) { diff --git a/physics/consistbraking.h b/physics/consistbraking.h index bef61ff4c..78794864a 100644 --- a/physics/consistbraking.h +++ b/physics/consistbraking.h @@ -63,6 +63,7 @@ class ConsistBrakeBlending double logTime{0.0}; double logInactiveTime{0.0}; int logCount{0}; + bool logUnavailable{false}; // the log couldn't be opened (no MEDLOGS folder): it isn't tried again }; } // namespace physics From 18d1c58994fe141d9f56aa131c9d5bf2aa88fa6e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 04:20:18 +0100 Subject: [PATCH 02/17] perf(world): FastGetTFromS reads the curve's t and slope of a point side by side TSegment kept the curve parameter t at equal steps of s (fTsBuffer) and the Hermite slopes at the same points (fTsSlope) in two vectors, and FastGetTFromS(), called for every axle of every vehicle on every step, read [i] and [i + 1] of both: four loads from two separate allocations. The two now go together in one vector of {t, slope} (fTs), so the interpolation touches one or two cache lines. The values and the arithmetic, in the same order, are unchanged. Tomaszewo (raj40821) 600 s in --test, seed 12345: FastGetTFromS was 1.2% of the main thread; sim 259.7 s median of 3 (255.0-271.3) against 268.3 s (262.5-279.2) before, which is about the run-to-run spread. The 14 physics logs and the event log are byte-identical, unit tests 1205/1205 with exact golden traces. --- world/Segment.cpp | 57 ++++++++++++++++++++++++----------------------- world/Segment.h | 10 ++++++--- 2 files changed, 36 insertions(+), 31 deletions(-) diff --git a/world/Segment.cpp b/world/Segment.cpp index 6e0326c33..f9ec7f85e 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -187,11 +187,11 @@ bool TSegment::InitChain(std::vector> Pieces) fDirection = -std::atan2(Point2.x - Point1.x, Point2.z - Point1.z); fStoop = std::atan2(Point2.y - Point1.y, fLength); fStep = fLength / iSegCount; - fTsBuffer.resize( iSegCount + 1 ); + fTs.resize( iSegCount + 1 ); for( int i = 0; i <= iSegCount; ++i ) { - fTsBuffer[ i ] = static_cast( i ) / iSegCount; + fTs[ i ].t = static_cast( i ) / iSegCount; + fTs[ i ].slope = fStep / fLength; } - fTsSlope.assign( iSegCount + 1, fStep / fLength ); return true; } @@ -204,28 +204,27 @@ std::size_t TSegment::piece_at(double const s) const void TSegment::InitTFromSInterpolateData() { // pre-compute the curve parameter t at equal distance intervals - fTsBuffer.resize( iSegCount + 1 ); - fTsBuffer[ 0 ] = 0.0; + fTs.resize( iSegCount + 1 ); + fTs[ 0 ].t = 0.0; for( int i = 1; i < iSegCount; ++i ) { - fTsBuffer[ i ] = GetTFromS( i * fStep ); + fTs[ i ].t = GetTFromS( i * fStep ); } - fTsBuffer[ iSegCount ] = 1.0; + fTs[ iSegCount ].t = 1.0; // pre-compute Hermite slopes dt/du = fStep / |B'(t)| for FastGetTFromS // (dt/ds = 1/|B'(t)|, scaled by fStep to the interval coordinate u) - fTsSlope.resize( iSegCount + 1 ); for( int i = 0; i <= iSegCount; ++i ) { // compute ds/dt derivative = |B'(t)| - double const speed = glm::length( GetFirstDerivative( fTsBuffer[ i ] ) ); + double const speed = glm::length( GetFirstDerivative( fTs[ i ].t ) ); // compute dt/du derivative = fStep / (ds/dt) - fTsSlope[ i ] = speed > 0.0 ? fStep / speed : 0.0; + fTs[ i ].slope = speed > 0.0 ? fStep / speed : 0.0; } // clamp slopes to keep t(s) monotone (PCHIP / Fritsch-Carlson condition) for( int i = 0; i <= iSegCount; ++i ) { double limit = std::numeric_limits::max(); - if( i > 0 ) { limit = std::min( limit, 3.0 * ( fTsBuffer[ i ] - fTsBuffer[ i - 1 ] ) ); } - if( i < iSegCount ) { limit = std::min( limit, 3.0 * ( fTsBuffer[ i + 1 ] - fTsBuffer[ i ] ) ); } - fTsSlope[ i ] = std::min( fTsSlope[ i ], limit ); + if( i > 0 ) { limit = std::min( limit, 3.0 * ( fTs[ i ].t - fTs[ i - 1 ].t ) ); } + if( i < iSegCount ) { limit = std::min( limit, 3.0 * ( fTs[ i + 1 ].t - fTs[ i ].t ) ); } + fTs[ i ].slope = std::min( fTs[ i ].slope, limit ); } } @@ -296,7 +295,7 @@ double TSegment::GetTFromS(double const s) const double TSegment::FastGetTFromS(double const s) const { // Faster version of GetTFromS: cubic Hermite interpolation using - // the precomputed values in fTsBuffer and slopes in fTsSlope. It + // the precomputed values and slopes in fTs. It // avoids the expensive RombergIntegral+Newton per call. Hermite // interpolation is C1-continuous, so no sudden speed changes when // moving from one interval to the next. @@ -310,10 +309,12 @@ double TSegment::FastGetTFromS(double const s) const double const u2 = u * u; double const u3 = u2 * u; double const h01 = -2.0 * u3 + 3.0 * u2; - double const t = ( ( 1.0 - h01 ) * fTsBuffer[ i ] + - ( u3 - 2.0 * u2 + u ) * fTsSlope [ i ] + - h01 * fTsBuffer[ i + 1 ] + - ( u3 - u2 ) * fTsSlope [ i + 1 ] ); + auto const &from { fTs[ i ] }; + auto const &to { fTs[ i + 1 ] }; + double const t = ( ( 1.0 - h01 ) * from.t + + ( u3 - 2.0 * u2 + u ) * from.slope + + h01 * to.t + + ( u3 - u2 ) * to.slope ); return t; } @@ -375,11 +376,11 @@ TSegment::find_nearest_point( glm::dvec3 const &Point ) const { auto const segmentpoint = std::clamp( nearest_segment_point( - glm::dvec3{ FastGetPoint( fTsBuffer[ segmentidx ] ) }, - glm::dvec3{ FastGetPoint( fTsBuffer[ segmentidx + 1 ] ) }, + glm::dvec3{ FastGetPoint( fTs[ segmentidx ].t ) }, + glm::dvec3{ FastGetPoint( fTs[ segmentidx + 1 ].t ) }, Point ) // point in range 0-1 on current segment - * ( fTsBuffer[ segmentidx + 1 ] - fTsBuffer[ segmentidx ] ) // segment length - + fTsBuffer[ segmentidx ], // segment offset + * ( fTs[ segmentidx + 1 ].t - fTs[ segmentidx ].t ) // segment length + + fTs[ segmentidx ].t, // segment offset 0.0, 1.0 ); // we clamp the range in case there's some floating point math inaccuracies auto const segmentdistance = glm::length2( Point - glm::dvec3{ FastGetPoint( segmentpoint ) } ); @@ -545,7 +546,7 @@ void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm:: }; void TSegment::plan_frame( double const Distance, glm::dvec3 &Point, glm::dvec3 &Across ) const { - if( fTsBuffer.empty() ) { + if( fTs.empty() ) { // never made into a path: tt_Cross and the like Point = Point1; Across = glm::dvec3 { 0.0 }; @@ -573,7 +574,7 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin, // standardowo tworzy triangle_strip dla prostego albo ich zestaw dla łuku // po modyfikacji - dla ujemnego (iNumShapePoints) w dodatkowych polach tabeli podany jest przekrój końcowy - if( fTsBuffer.empty() ) + if( fTs.empty() ) return false; // prowizoryczne zabezpieczenie przed wysypem - ustalić faktyczną przyczynę glm::vec3 pos1; @@ -602,7 +603,7 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin, tv1 = 1.0; // Ra: to by można było wyliczać dla odcinka, wyglądało by lepiej s = static_cast(fStep * iSkip); // iSkip - ile odcinków z początku pominąć int i = iSkip; // domyślnie 0 - t = static_cast(fTsBuffer[ i ]); // tabela wattości t dla segmentów + t = static_cast(fTs[ i ].t); // tabela wattości t dla segmentów // BUG: length of spline can be 0, we should skip geometry generation for such cases fOffset = static_cast(0.1 / fLength); // pierwsze 10cm pos1 = glm::dvec3{ FastGetPoint( t ) - Origin }; // wektor początku segmentu @@ -653,7 +654,7 @@ bool TSegment::RenderLoft( gfx::vertex_array &Output, glm::dvec3 const &Origin, tv1 = clamp_circular( tv1, 1.0f ); tv2 = tv1 - step / texturelength; // mapowanie na końcu segmentu - t = static_cast(fTsBuffer[ i ]); // szybsze od GetTFromS(s); + t = static_cast(fTs[ i ].t); // szybsze od GetTFromS(s); pos2 = glm::dvec3{ FastGetPoint( t ) - Origin }; dir = glm::dvec3{ FastGetDirection( t, fOffset ) }; // nowy wektor kierunku parallel2 = glm::vec3{ -dir.z, 0.f, dir.x }; // wektor poprzeczny @@ -769,7 +770,7 @@ void TSegment::roll_vertex( gfx::basic_vertex &Vertex, glm::vec3 const &Position bool TSegment::RenderLoftSteps( gfx::vertex_array &Output, glm::dvec3 const &Origin, gfx::vertex_array const &ShapePoints, double fTextureLength, int const Steps ) const { - if( fTsBuffer.empty() || Steps < 1 || fLength <= 0.0 ) + if( fTs.empty() || Steps < 1 || fLength <= 0.0 ) return false; auto const shapepoints { ShapePoints.size() / 2 }; @@ -1431,7 +1432,7 @@ gfx::vertex_array const &low_section::profile_at( gfx::vertex_array const &Shape bool TSegment::RenderLoftSpan( gfx::vertex_array &Output, glm::dvec3 const &Origin, gfx::vertex_array const &ShapePoints, loft_span const &Span ) const { - if( fTsBuffer.empty() || Span.to - Span.from < 0.001 || ShapePoints.empty() ) + if( fTs.empty() || Span.to - Span.from < 0.001 || ShapePoints.empty() ) return false; auto const stations { loft_stations( Span, ShapePoints, std::max( fStep, 0.2 ), m_dense ) }; diff --git a/world/Segment.h b/world/Segment.h index 88aa9adff..26ee986d1 100644 --- a/world/Segment.h +++ b/world/Segment.h @@ -116,8 +116,12 @@ class TSegment }; setting m_setting; double fLength { -1.0 }; // długość policzona - std::vector fTsBuffer; // wartości parametru krzywej t dla równych odcinków s - std::vector fTsSlope; // nachylenie dt/du (= dt/ds * fStep) w tych samych punktach + // the curve at equal intervals of s, for FastGetTFromS(): the two it reads of a point side by side, in one cache line + struct ts_point { + double t; // wartość parametru krzywej t dla równych odcinków s + double slope; // nachylenie dt/du (= dt/ds * fStep) w tym punkcie + }; + std::vector fTs; double fStep = 0.0; int iSegCount = 0; // ilość odcinków do rysowania krzywej double fDirection = 0.0; // Ra: kąt prostego w planie; dla łuku kąt od Point1 @@ -275,7 +279,7 @@ public: inline int RaSegCount() const { - return fTsBuffer.empty() ? 1 : iSegCount; }; + return fTs.empty() ? 1 : iSegCount; }; void render_lines(std::vector &out, float quality = 1.0f) const; From e8b47b7b1ce5c057bf0be1e444e251c8d7db4f1d Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 05:16:55 +0100 Subject: [PATCH 03/17] perf(physics): the ESt3 valve and its relays read a pressure once where it can't change between reads TNESt3::GetPF() and the relays it steps (TPrzekladnik, TRapid, TPrzekCiagly, TPrzekED ::Update) read the same pressures several times through virtual P() calls: TRura::P() passes the call on down the chain of relays to the cylinder. A reservoir's pressure (Vol / Cap) changes only in Act() and CreatePress(); Flow() only adds to the pending change. So between two reads with only Flow() calls in between the value is the same, and it's read once now: - GetPF(): the cylinder pressure after the two Flow() calls of the release/apply is BCP, read at the start (CheckState() can recreate the pressure of ValveRes only, which isn't in the relay chain); CVs(BCP) was worked out twice with nothing but Flow() calls between, now once. - the relays: their own P() read once instead of up to four times, TPrzekED's Next->P() once. The arithmetic and its order are unchanged. Tomaszewo (raj40821) 600 s in --test, seed 12345: GetPF was 2.9% of the main thread (inclusive) before the series; sim 275.3 s in one run against 259.7 s (median of 3, 255.0-271.3) the step before: no gain beyond the run-to-run spread (about +-5%) shows in the run time. The 14 physics logs and the event log are byte-identical, unit tests 1205/1205 with exact golden traces. --- physics/oerlikonest.cpp | 42 ++++++++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 17 deletions(-) diff --git a/physics/oerlikonest.cpp b/physics/oerlikonest.cpp index 70c3d4f8e..4eab8d582 100644 --- a/physics/oerlikonest.cpp +++ b/physics/oerlikonest.cpp @@ -66,12 +66,14 @@ void TPrzekladnik::Update(double dt) double BCP{ Next->P() }; double BVP{ BrakeRes->P() }; + // the pressure of the relay itself, read once: nothing changes it before the flows are applied (Act()) + double const ownP{ P() }; - if ( BCP > P() ) - dV = -PFVd(BCP, 0, d2A(10), P()) * dt; + if ( BCP > ownP ) + dV = -PFVd(BCP, 0, d2A(10), ownP) * dt; else { - if( BCP < P() ) - dV = PFVa( BVP, BCP, d2A( 10 ), P() ) * dt; + if( BCP < ownP ) + dV = PFVa( BVP, BCP, d2A( 10 ), ownP ) * dt; else dV = 0; } @@ -120,10 +122,11 @@ void TRapid::Update(double dt) ActMult = 1.0; } - if (BCP * RapidMult > P() * ActMult) - dV = -PFVd(BCP, 0, DL, P() * ActMult / RapidMult) * dt; - else if (BCP * RapidMult < P() * ActMult) - dV = PFVa(BVP, BCP, DN, P() * ActMult / RapidMult) * dt; + double const ownP{ P() }; + if (BCP * RapidMult > ownP * ActMult) + dV = -PFVd(BCP, 0, DL, ownP * ActMult / RapidMult) * dt; + else if (BCP * RapidMult < ownP * ActMult) + dV = PFVa(BVP, BCP, DN, ownP * ActMult / RapidMult) * dt; else dV = 0.0; @@ -145,10 +148,11 @@ void TPrzekCiagly::Update(double dt) double const BCP{ Next->P() }; double dV; - if ( BCP > P() * Mult) - dV = -PFVd(BCP, 0, d2A(8.0), P() * Mult) * dt; - else if (BCP < P() * Mult) - dV = PFVa(BVP, BCP, d2A(8.0), P() * Mult) * dt; + double const ownP{ P() }; + if ( BCP > ownP * Mult) + dV = -PFVd(BCP, 0, d2A(8.0), ownP * Mult) * dt; + else if (BCP < ownP * Mult) + dV = PFVa(BVP, BCP, d2A(8.0), ownP * Mult) * dt; else dV = 0.0; @@ -193,10 +197,11 @@ void TPrzekED::SetP(double P) void TPrzekED::Update(double dt) { - if (Next->P() > MaxP) + // the pressure after the relay, read once: the flows change it only once applied (Act()) + if (double const nextP{ Next->P() }; nextP > MaxP) { BrakeRes->Flow(dVol); - Next->Flow(PFVd(Next->P(), 0, d2A(10.0) * dt, MaxP)); + Next->Flow(PFVd(nextP, 0, d2A(10.0) * dt, MaxP)); } else Next->Flow(dVol); @@ -232,7 +237,8 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr dV = 0.0; // BrakeCyl.Flow(-dV); Przekladniki[1]->Flow(-dV); - if ( (BrakeStatus & b_on) == b_on && Przekladniki[1]->P() * HBG300 < MaxBP ) + // the flows above change the pressure of the cylinder only once applied (Act()), it's still BCP + if ( (BrakeStatus & b_on) == b_on && BCP * HBG300 < MaxBP ) dV = PF( BVP, BCP, Nozzles[dTN] * (nastG + 2.0 * (BCP < Podskok ? 1.0 : 0.0)) + Nozzles[dON] * (1.0 - nastG) ) * dt * (0.1 + 4.9 * std::min( 0.2, cel - BCP ) ); @@ -262,8 +268,11 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr if( PrzekPZZ != nullptr ) PrzekPZZ->SetLBP(LBP); + // the nozzle of the control reservoir's filler, the same for both flows below: the flows change the pressures it + // goes by only once applied (Act()) + double const temp = CVs(BCP); // przeplyw testowy miedzypojemnosci - dV = PF(MPP, VVP, BVs(BCP)) + PF(MPP, CVP, CVs(BCP)); + dV = PF(MPP, VVP, BVs(BCP)) + PF(MPP, CVP, temp); if (MPP - 0.05 > BVP) dV += PF(MPP - 0.05, BVP, Nozzles[dPT] * nastG + (1.0 - nastG) * Nozzles[dPO]); if (MPP > VVP) @@ -271,7 +280,6 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr Miedzypoj->Flow(dV * dt * 0.15); // przeplyw ZS <-> PG - double const temp = CVs(BCP); dV = PF(CVP, MPP, temp) * dt; CntrlRes->Flow(dV); ValveRes->Flow(-0.02 * dV); From 0c4aa1fe30e9d311bee6bb5d091cad39fa4059eb Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 05:58:54 +0100 Subject: [PATCH 04/17] perf(physics): the hose exchange goes through the vehicles of each train only exchange_through_hoses() takes the air exchange through the brake and the main reservoir hoses train by train, each in its own number of sub-steps (up to 10). For every sub-step of every train it went through the whole list of vehicles, all of the scenery's in update_brake_pipes(), and looked into each one's pipe to tell whether it belongs to that train: trains x sub-steps x vehicles reads of vehicles scattered in memory, twice a step (both pipes). In Tomaszewo, with 129 trainsets, this alone was 38.6% of the main thread. The vehicles of each train are now put in a list once per call (a counting sort of the train numbers hose_trains() gives, keeping the order of the list within a train), and a sub-step goes through its train's list. The membership is the one the loop tested (a vehicle is in a train when its pipe stepped, which nothing changes during the exchange), the trains, the sub-steps and the vehicles within a train come in the same order, so every Flow()/Act() happens in the same order with the same values. Tomaszewo (raj40821) 600 s in --test, seed 12345: sim 206.7 s against 275.3 s the step before (one run each, same session, -25%); wall 365.8 s against 447.5 s (the load, ~150-165 s, is unchanged). In an earlier series 3 runs gave 187.3 s median (183.0-195.6) against 265.6 s. The 14 physics logs and the event log are byte-identical, unit tests 1205/1205 with exact golden traces. --- physics/components/pneumatics.cpp | 35 +++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 335616420..42e55c8f0 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -1446,18 +1446,41 @@ void exchange_through_hoses(std::vector const &Vehicles, tra } substeps[trains[index]] = std::max(substeps[trains[index]], hose_substeps(*Vehicles[index], trainPipe, dt)); } + // the vehicles of each train, in the order of the list: the ones of train t are members[firsts[t]] up to + // members[firsts[t + 1]], not included. going through them alone, a sub-step of a train costs its own vehicles, + // not a look at every vehicle of the list (all of the scenery's, in update_brake_pipes()), and takes them in the + // same order as that did + std::vector firsts(substeps.size() + 1, 0); + for (auto const train : trains) + { + if (train < substeps.size()) + { + ++firsts[train + 1]; + } + } + for (std::size_t train = 0; train < substeps.size(); ++train) + { + firsts[train + 1] += firsts[train]; + } + std::vector members(firsts.back()); + { + auto next{firsts}; + for (std::size_t index = 0; index < Vehicles.size(); ++index) + { + if (trains[index] < substeps.size()) + { + members[next[trains[index]]++] = index; + } + } + } for (std::size_t train = 0; train < substeps.size(); ++train) { auto const substep{dt / substeps[train]}; for (auto i = 0; i < substeps[train]; ++i) { - for (std::size_t index = 0; index < Vehicles.size(); ++index) + for (auto member = firsts[train]; member < firsts[train + 1]; ++member) { - if (false == (Vehicles[index]->*trainPipe.pipe).CouplersPending() || trains[index] != train) - { - continue; - } - auto *vehicle{Vehicles[index]}; + auto *vehicle{Vehicles[members[member]]}; auto &pipe{*(vehicle->*trainPipe.pipe).reservoir}; pipe.Act(); // what the neighbours have sent in the meantime (vehicle->*trainPipe.pipe).SetPressure(pipe.P()); From aa9fc1b6f34f4574ae60fcf42b089af0bbb01fd4 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 08:15:16 +0100 Subject: [PATCH 05/17] perf(physics): the engine of a group of vehicles stepped in parallel is seeded at its first draw vehicle_table::update_steps_parallel() gives each group of vehicles an engine of Random() of its own, seeded from the run's engine and the group, so the draws are the same whichever thread takes the group. It built a std::mt19937 from a std::seed_seq for every group in every step: seed_seq::generate filling the 624 words of the state was 2.4% of the main thread and most of what the worker threads did (5263 of their non-waiting samples) on Tomaszewo, where most groups (parked wagons, cars) draw nothing. The group now gets a lazy_random_engine (utilities/lazyrandom.h) holding the two numbers, which Random() seeds the same way (std::seed_seq of the two) at the group's first draw. A group that draws gets the same numbers as before, one that doesn't skips the seeding. Ported from a local branch of 2026-11-28 (perf/parallel-group-random-engine-lazy-seed, on the layout before #531), with its tests: the lazy engine draws as one seeded up front from the same numbers, is seeded at the first draw only, and stands ahead of the thread's engine while it's set. 600 s in --test, seed 12345, one run each: Tomaszewo (raj40821) sim 151.5 s against 206.7 s the step before (-27%); L107 (linia_107_objazdy, binary terrain, gfxrenderer null) sim 20.5 s against 31.1 s. The physics logs (14 and 9) and the event logs are byte-identical to staging's, unit tests 1207/1207 with exact golden traces. --- tests/unit/test_random_engine.cpp | 71 +++++++++++++++++++++++++++++++ utilities/lazyrandom.h | 30 +++++++++++++ utilities/utilities.cpp | 21 +++++++++ vehicle/dynamic/vehicletable.cpp | 13 +++--- 4 files changed, 130 insertions(+), 5 deletions(-) create mode 100644 tests/unit/test_random_engine.cpp create mode 100644 utilities/lazyrandom.h diff --git a/tests/unit/test_random_engine.cpp b/tests/unit/test_random_engine.cpp new file mode 100644 index 000000000..da673ef4d --- /dev/null +++ b/tests/unit/test_random_engine.cpp @@ -0,0 +1,71 @@ +#include "stdafx.h" + +#include "doctest.h" + +#include "utilities/utilities.h" +#include "utilities/lazyrandom.h" + +#include +#include + +namespace +{ +// what Random() draws in the calling thread with the engine set before, n times +std::vector draws(int const Count) +{ + std::vector result; + for (int i = 0; i < Count; ++i) + result.push_back(Random(0.0, 1.0)); + return result; +} +} // namespace + +TEST_CASE("random engine: the lazily seeded engine draws as one seeded up front from the same numbers") +{ + std::pair const seeds[]{{0u, 0u}, {12345u, 7u}, {0xFFFFFFFFu, 4096u}}; + for (auto const &seed : seeds) + { + CAPTURE(seed.first); + CAPTURE(seed.second); + std::seed_seq eagerseed{seed.first, seed.second}; + std::mt19937 eager{eagerseed}; // NOSONAR: randomness of the simulation, not of anything security-relevant + set_thread_random_engine(&eager); + auto const expected{draws(100)}; + set_thread_random_engine(nullptr); + + lazy_random_engine lazy; + lazy.seed[0] = seed.first; + lazy.seed[1] = seed.second; + set_thread_lazy_random_engine(&lazy); + auto const actual{draws(100)}; + set_thread_lazy_random_engine(nullptr); + + CHECK(actual == expected); + } +} + +TEST_CASE("random engine: the lazy engine is seeded at the first draw only, and stands ahead of the thread's engine") +{ + std::mt19937 threadengine{1u}; // NOSONAR: randomness of the simulation, not of anything security-relevant + auto const untouched{threadengine}; + set_thread_random_engine(&threadengine); + + lazy_random_engine lazy; + lazy.seed[0] = 3u; + lazy.seed[1] = 5u; + set_thread_lazy_random_engine(&lazy); + CHECK(thread_lazy_random_engine() == &lazy); + // a group that draws nothing never seeds it + CHECK_FALSE(lazy.engine.has_value()); + static_cast(Random(0.0, 1.0)); + CHECK(lazy.engine.has_value()); + // the draw came from the lazy engine, the one of the thread is left as it was + CHECK(threadengine == untouched); + + set_thread_lazy_random_engine(nullptr); + CHECK(thread_lazy_random_engine() == nullptr); + // without the lazy engine the draws come from the thread's engine again + static_cast(Random(0.0, 1.0)); + CHECK_FALSE(threadengine == untouched); + set_thread_random_engine(nullptr); +} diff --git a/utilities/lazyrandom.h b/utilities/lazyrandom.h new file mode 100644 index 000000000..aed55184b --- /dev/null +++ b/utilities/lazyrandom.h @@ -0,0 +1,30 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +// an engine of Random() seeded from two numbers (std::seed_seq) only when the first draw needs it: seeding a std::mt19937 +// fills its whole state (624 numbers), which took longer than the steps of most of the groups of vehicles it was made for +// in every frame (vehicle_table::update_steps_parallel()), and most of them (parked wagons, cars) draw nothing + +#pragma once + +#include +#include +#include + +struct lazy_random_engine +{ + std::uint32_t seed[2]{}; + std::optional engine; // NOSONAR: randomness of the simulation, not of anything security-relevant +}; + +// the engine Random() draws from in the calling thread ahead of the one of set_thread_random_engine(), or none for that one +// again. its draws are the ones of a std::mt19937 built from std::seed_seq{ seed[0], seed[1] } up front +void set_thread_lazy_random_engine(lazy_random_engine *Engine); +// the engine set for the calling thread by set_thread_lazy_random_engine(), or none +lazy_random_engine *thread_lazy_random_engine(); diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 1adb80a5b..8b7c3868b 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -28,6 +28,7 @@ Copyright (C) 2007-2014 Maciej Cierniak //#endif #include "utilities/utilities.h" +#include "utilities/lazyrandom.h" #include "utilities/Globals.h" #include "utilities/parser.h" #include "utilities/U8.h" @@ -181,13 +182,33 @@ bool ClearFlag(int &Flag, int const Value) namespace { thread_local std::mt19937 *t_random_engine{nullptr}; // NOSONAR: randomness of the simulation, not of anything security-relevant +thread_local lazy_random_engine *t_lazy_random_engine{nullptr}; std::mt19937 &random_engine() // NOSONAR: randomness of the simulation, not of anything security-relevant { + if (t_lazy_random_engine != nullptr) + { + if (false == t_lazy_random_engine->engine.has_value()) + { + std::seed_seq seed{t_lazy_random_engine->seed[0], t_lazy_random_engine->seed[1]}; + t_lazy_random_engine->engine.emplace(seed); + } + return *t_lazy_random_engine->engine; + } return t_random_engine != nullptr ? *t_random_engine : Global.random_engine; } } // namespace +void set_thread_lazy_random_engine(lazy_random_engine *Engine) +{ + t_lazy_random_engine = Engine; +} + +lazy_random_engine *thread_lazy_random_engine() +{ + return t_lazy_random_engine; +} + void set_thread_random_engine(std::mt19937 *Engine) // NOSONAR: randomness of the simulation, not of anything security-relevant { t_random_engine = Engine; diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index 9d0e42a22..cc22de88d 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -41,6 +41,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/Timer.h" #include "utilities/workerpool.h" +#include "utilities/lazyrandom.h" #include "utilities/Logs.h" #include "utilities/glmHelpers.h" #include "Console.h" @@ -671,10 +672,12 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio auto const seed { static_cast( Global.random_engine() ) }; auto const steps = [ & ]( std::uint32_t const Group ) { auto const &members { m_groups[ Group ] }; - std::seed_seq groupseed { seed, members.front() }; - std::mt19937 engine { groupseed }; // NOSONAR: randomness of the simulation, not of anything security-relevant - auto *const threadengine { thread_random_engine() }; - set_thread_random_engine( &engine ); + // seeded at the first draw, if the group makes one: the seeding took longer than the steps of most groups + lazy_random_engine engine; + engine.seed[ 0 ] = seed; + engine.seed[ 1 ] = members.front(); + auto *const threadengine { thread_lazy_random_engine() }; + set_thread_lazy_random_engine( &engine ); // the hoses join only vehicles coupled with each other, which are in one group: the air they carry is exchanged // within the group after each step, as update_brake_pipes() does for all the vehicles in one thread std::vector pipes; @@ -701,7 +704,7 @@ vehicle_table::update_steps_parallel( double const Deltatime, int const Iteratio // the vehicles going by one step take it with the time of all of them m_items[ index ]->UpdateForce( coarse( index ) ? totaltime : Deltatime ); } - set_thread_random_engine( threadengine ); }; + set_thread_lazy_random_engine( threadengine ); }; Workers().run( m_threadgroups.size(), Threads, From dde512da23a2b247dfab73756040b7828051f02d Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 08:43:31 +0100 Subject: [PATCH 06/17] perf(test): no imgui frames in the test mode The window of the test mode is hidden and the renderer is the null one, nobody sees the ui. Still every frame began an imgui frame, whose ImGui_ImplGlfw_NewFrame() polled the window, the mouse (WindowFromPoint) and the gamepads, and the null renderer ended it: ~2.2% of the main thread, with NtUserWindowFromPoint another ~0.5%. In the test mode eu07_application::begin_ui_frame() and render_ui() now do nothing; outside of it nothing changes. ui_layer::shutdown() ends the last frame only if one was begun, as none is in the test mode (it crashed in imgui's error recovery at the exit). 600 s in --test, seed 12345, one run each: Tomaszewo (raj40821) sim 137.4 s against 151.5 s the step before (-9%); L107 (linia_107_objazdy) sim 18.8 s against 20.5 s. The physics logs (14 and 9) and the event logs are byte-identical to staging's, unit tests 1207/1207 with exact golden traces. --- application/application.cpp | 6 ++++-- application/uilayer.cpp | 4 +++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/application/application.cpp b/application/application.cpp index fa74c3d7d..66192746d 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -991,7 +991,7 @@ void eu07_application::render_ui() return; } - if (m_modestack.empty()) + if (m_modestack.empty() || Global.test.enabled) { return; } @@ -1002,7 +1002,9 @@ void eu07_application::render_ui() void eu07_application::begin_ui_frame() { - if (m_modestack.empty()) + // in the test mode nobody sees the window (hidden, the null renderer): no ui frames, whose start polled the window, + // the mouse and the gamepads every frame through imgui's glfw backend + if (m_modestack.empty() || Global.test.enabled) { return; } diff --git a/application/uilayer.cpp b/application/uilayer.cpp index c24291047..d74513205 100644 --- a/application/uilayer.cpp +++ b/application/uilayer.cpp @@ -440,7 +440,9 @@ bool ui_layer::init(GLFWwindow *Window) void ui_layer::shutdown() { - ImGui::EndFrame(); + // the frame begun last, if there was one: the test mode begins none (eu07_application::begin_ui_frame()) + if (GImGui != nullptr && GImGui->WithinFrameScope) + ImGui::EndFrame(); // the vulkan renderer is gone by now (its backend of imgui went with it) if (auto *renderer{GfxRenderer->GetImguiRenderer()}) From 89de7380eec651297f7d94445afe5e0c196f3f51 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 09:01:34 +0100 Subject: [PATCH 07/17] perf(physics): the trains of the hose exchange are kept from one step to the next exchange_through_hoses() worked out on every call which vehicles the brake and the main reservoir hoses join into trains (hose_trains(): the list sorted by address, a search through the couplers), and laid them out train by train: ~2.7% of the main thread on Tomaszewo, for trains which change only with a coupling, a vehicle going to sleep or waking up, or one added or taken away. vehicle_table::update_brake_pipes(), which passes all the vehicles of the scenery in every step, now keeps them in a physics::hose_trains_cache (physics/components/hosetrains.h) together with what they were worked out from: of each vehicle of the list, whether it stepped the pipe and the neighbour the hose of each end joins it to. On every step that is gathered again (one pass over the list) and compared: the trains are worked out again unless it's all the same, so they're always the ones hose_trains() gives. The groups stepped in parallel (update_steps_parallel()) and physics::Vehicle::UpdatePipeCouplers() work them out on each call as before. hose_substeps() goes by the pressures, which change in every step, and is left as it is. The unit tests' consist steps its brake pipes the way update_brake_pipes() does now, with the trains kept, so the golden traces (recorded on staging) check the kept trains, the uncouplings of the tests included. 600 s in --test, seed 12345, one run each: Tomaszewo (raj40821) sim 134.9 s against 137.4 s the step before (-1.8%); L107 (linia_107_objazdy) sim 18.1 s against 18.8 s. The physics logs (14 and 9) and the event logs are byte-identical to staging's, unit tests 1207/1207 with exact golden traces. --- physics/components/hosetrains.h | 55 ++++++++++++++ physics/components/pneumatics.cpp | 122 +++++++++++++++++++++--------- tests/unit/consist.cpp | 2 +- tests/unit/consist.h | 3 + vehicle/dynamic/vehicletable.cpp | 5 +- 5 files changed, 150 insertions(+), 37 deletions(-) create mode 100644 physics/components/hosetrains.h diff --git a/physics/components/hosetrains.h b/physics/components/hosetrains.h new file mode 100644 index 000000000..64cd66250 --- /dev/null +++ b/physics/components/hosetrains.h @@ -0,0 +1,55 @@ +/* +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 trains of the air exchange through the hoses (physics::Vehicle::UpdatePipeCouplers()) kept from one step to the next + +#pragma once + +#include +#include +#include + +namespace physics +{ + +class Vehicle; + +// the trains of the hose exchange of the brake and the main reservoir pipe, worked out from the list of vehicles given, +// which of them stepped the pipe and which neighbours their hoses join them to. they change only with a coupling or an +// uncoupling, a vehicle going to sleep or waking up, or one added or taken away, so they're kept while all of that +// stays as it was in the step before, which is checked on every step: kept or worked out again, they're the same +class hose_trains_cache +{ + public: + // what the trains of a pipe were worked out from, for one vehicle of the list + struct input + { + Vehicle const *vehicle{nullptr}; + std::array joined{nullptr, nullptr}; // the neighbour the hose of each end joins it to, or none + bool pending{false}; // the vehicle stepped the pipe + bool operator==(input const &) const = default; + }; + // the trains of a pipe + struct pipe + { + std::vector inputs; + std::vector trains; // the train of each vehicle of the list, none for one which didn't step the pipe + std::vector firsts; // train t is members[firsts[t]] up to members[firsts[t + 1]], not included + std::vector members; // the indices in the list of the vehicles of each train, in the order of the list + bool valid{false}; + }; + pipe brake; + pipe main; +}; + +// physics::Vehicle::UpdatePipeCouplers(), with the trains kept in Cache from one call to the next. for one list of +// vehicles which comes back in every step (all of the scenery's, vehicle_table::update_brake_pipes()) +void UpdatePipeCouplers(std::vector const &Vehicles, double dt, hose_trains_cache &Cache); + +} // namespace physics diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 42e55c8f0..0bf68e90b 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -28,6 +28,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "physics/components/internal.h" +#include "physics/components/hosetrains.h" // Nastawianie hamulców @@ -1425,54 +1426,99 @@ std::vector hose_trains(std::vector const &Vehi return trains; } +// the trains of the pipe laid out: the vehicles of each train, in the order of the list, for going through a train alone. a +// sub-step of a train then costs its own vehicles, not a look at every vehicle of the list (all of the scenery's, in +// update_brake_pipes()), and takes them in the same order as that did +void lay_out_trains(physics::hose_trains_cache::pipe &Layout, std::vector Trains) +{ + Layout.trains = std::move(Trains); + std::size_t count{0}; + for (auto const train : Layout.trains) + { + if (train != std::numeric_limits::max()) + { + count = std::max(count, train + 1); + } + } + Layout.firsts.assign(count + 1, 0); + for (auto const train : Layout.trains) + { + if (train < count) + { + ++Layout.firsts[train + 1]; + } + } + for (std::size_t train = 0; train < count; ++train) + { + Layout.firsts[train + 1] += Layout.firsts[train]; + } + Layout.members.resize(Layout.firsts.back()); + auto next{Layout.firsts}; + for (std::size_t index = 0; index < Layout.trains.size(); ++index) + { + if (Layout.trains[index] < count) + { + Layout.members[next[Layout.trains[index]]++] = index; + } + } +} + +// what hose_trains() goes by, of each vehicle of the list: whether it stepped the pipe and the neighbours its hoses join it to +void hose_inputs(std::vector &Inputs, std::vector const &Vehicles, train_pipe const &trainPipe) +{ + Inputs.resize(Vehicles.size()); + for (std::size_t index = 0; index < Vehicles.size(); ++index) + { + auto const &vehicle{*Vehicles[index]}; + auto &input{Inputs[index]}; + input.vehicle = &vehicle; + input.pending = (vehicle.*trainPipe.pipe).CouplersPending(); + std::size_t end{0}; + for (auto const &hose : vehicle.Couplers) + { + input.joined[end++] = (hose.Connected != nullptr && hose.CouplingFlag.HasAll(trainPipe.hose)) ? hose.Connected : nullptr; + } + } +} + // the air exchange through the hoses of the pipe, for the vehicles which stepped it since the last call, in the order // they stepped: each train in as many sub-steps of dt as its vehicle needing the most of them takes, each going through // its vehicles one after another, as the step of the vehicles does. the air of a train stays in it, so a train comes out // the same whichever other vehicles are exchanged in the same call: all of them, or the ones of a group of -// vehicle_table::update_steps_parallel() -void exchange_through_hoses(std::vector const &Vehicles, train_pipe const &trainPipe, double const dt) +// vehicle_table::update_steps_parallel(). with a Cache, the trains of the call before are taken again when what they +// were worked out from is the same +void exchange_through_hoses(std::vector const &Vehicles, train_pipe const &trainPipe, double const dt, physics::hose_trains_cache::pipe *Cache = nullptr) { - auto const trains{hose_trains(Vehicles, trainPipe)}; - std::vector substeps; + physics::hose_trains_cache::pipe fresh; + auto *layout{&fresh}; + if (Cache != nullptr) + { + std::vector inputs; + hose_inputs(inputs, Vehicles, trainPipe); + if (false == Cache->valid || inputs != Cache->inputs) + { + lay_out_trains(*Cache, hose_trains(Vehicles, trainPipe)); + Cache->inputs = std::move(inputs); + Cache->valid = true; + } + layout = Cache; + } + else + { + lay_out_trains(fresh, hose_trains(Vehicles, trainPipe)); + } + auto const &trains{layout->trains}; + auto const &firsts{layout->firsts}; + auto const &members{layout->members}; + std::vector substeps(firsts.size() - 1, 1); for (std::size_t index = 0; index < Vehicles.size(); ++index) { if (false == (Vehicles[index]->*trainPipe.pipe).CouplersPending()) { continue; } - if (substeps.size() <= trains[index]) - { - substeps.resize(trains[index] + 1, 1); - } substeps[trains[index]] = std::max(substeps[trains[index]], hose_substeps(*Vehicles[index], trainPipe, dt)); } - // the vehicles of each train, in the order of the list: the ones of train t are members[firsts[t]] up to - // members[firsts[t + 1]], not included. going through them alone, a sub-step of a train costs its own vehicles, - // not a look at every vehicle of the list (all of the scenery's, in update_brake_pipes()), and takes them in the - // same order as that did - std::vector firsts(substeps.size() + 1, 0); - for (auto const train : trains) - { - if (train < substeps.size()) - { - ++firsts[train + 1]; - } - } - for (std::size_t train = 0; train < substeps.size(); ++train) - { - firsts[train + 1] += firsts[train]; - } - std::vector members(firsts.back()); - { - auto next{firsts}; - for (std::size_t index = 0; index < Vehicles.size(); ++index) - { - if (trains[index] < substeps.size()) - { - members[next[trains[index]]++] = index; - } - } - } for (std::size_t train = 0; train < substeps.size(); ++train) { auto const substep{dt / substeps[train]}; @@ -1530,6 +1576,12 @@ void physics::Vehicle::UpdatePipeCouplers(std::vector const exchange_through_hoses(Vehicles, main_reservoir_pipe, dt); } +void physics::UpdatePipeCouplers(std::vector const &Vehicles, double const dt, hose_trains_cache &Cache) +{ + exchange_through_hoses(Vehicles, brake_pipe, dt, &Cache.brake); + exchange_through_hoses(Vehicles, main_reservoir_pipe, dt, &Cache.main); +} + bool physics::Vehicle::UpdateStopBrakeRelease(double const Demand, double const Dt) { if (Demand <= 0.0) diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index 796943c7d..d6d0f1a41 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -100,7 +100,7 @@ void consist::update_brake_pipes(double Dt) const { for (auto const &vehicle : m_vehicles) { vehicles.push_back(&vehicle->physics()); } - physics::Vehicle::UpdatePipeCouplers(vehicles, Dt); + physics::UpdatePipeCouplers(vehicles, Dt, m_hosetrains); } void consist::run(double Seconds, track const &Track, double Dt) { diff --git a/tests/unit/consist.h b/tests/unit/consist.h index 73daa6294..7d2cbbd69 100644 --- a/tests/unit/consist.h +++ b/tests/unit/consist.h @@ -5,6 +5,7 @@ #include #include "vehicle.h" +#include "physics/components/hosetrains.h" class TDynamicObject; @@ -53,6 +54,8 @@ private: // the game's object can't be made without the rest of the game, so it's a stand-in: storage of its size // with that one member set, never constructed, which only the physics ever looks into std::vector> m_objects; + // the trains of the hoses kept from one step to the next, as vehicle_table::update_brake_pipes() keeps them + mutable physics::hose_trains_cache m_hosetrains; }; } // namespace test diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index cc22de88d..c36ec47da 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -42,6 +42,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/workerpool.h" #include "utilities/lazyrandom.h" +#include "physics/components/hosetrains.h" #include "utilities/Logs.h" #include "utilities/glmHelpers.h" #include "Console.h" @@ -568,7 +569,9 @@ vehicle_table::update_brake_pipes( double const Deltatime ) { m_brakepipes.push_back( vehicle->physics ); } } - physics::Vehicle::UpdatePipeCouplers( m_brakepipes, Deltatime ); + // the trains of the hoses of all the vehicles change seldom, they're kept from one step to the next while they stay + static physics::hose_trains_cache hosetrains; + physics::UpdatePipeCouplers( m_brakepipes, Deltatime, hosetrains ); } // records the odometer states of the vehicles and saves them for the next sessions (eu07/maszyna#72) From 10429bd35396b242100c164ce9e26a52a276e968 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 10:26:37 +0100 Subject: [PATCH 08/17] perf(test): the counts and times of the vehicles for the debug panel aren't taken in the test mode vehicle_table::update() went through all the vehicles twice in every step only to count them for the debug panel (kinds, standing, awake, ai, active), and timed every vehicle in the step loops with steady_clock::now() (lap()), all of it shown only by the debug panel, which the test mode never draws (~2% of the main thread in steady_clock::now / QueryPerformanceCounter). In the test mode the first loop now runs only for the coarse steps of road vehicles (physics.roadlod), the second one not at all, and lap() doesn't time. Outside the test mode nothing changes. 600 s in --test, seed 12345, one run each: Tomaszewo (raj40821) sim 131.1 s against 134.9 s the step before (-2.8%); L107 (linia_107_objazdy) sim 18.5 s against 18.1 s (within the spread). The physics logs (14 and 9) and the event logs are byte-identical to staging's, unit tests 1207/1207 with exact golden traces. --- vehicle/dynamic/vehicletable.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index c36ec47da..82a06fe66 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -199,12 +199,16 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { && Global.network_servers.empty() && ( false == Global.network_client.has_value() ) }; auto const camera { Global.pCamera.Pos }; - for( std::size_t index = 0; index < m_items.size(); ++index ) { + // the counts and the times by kind are for the debug panel only, which the test mode doesn't show: there the loop is + // gone through only for the coarse steps, and the vehicles aren't timed + auto const counted { false == Global.test.enabled }; + for( std::size_t index = 0; ( counted || roadlod ) && index < m_items.size(); ++index ) { auto const *vehicle { m_items[ index ] }; auto const road { ( vehicle->physics->CategoryFlag & 2 ) != 0 }; auto const distant { glm::length2( vehicle->GetPosition() - camera ) > Timer::subsystem.VEHICLE_NEAR * Timer::subsystem.VEHICLE_NEAR }; kinds[ index ] = static_cast( ( road ? 2 : 0 ) + ( distant ? 1 : 0 ) ); coarse[ index ] = static_cast( roadlod && road && distant && ( false == vehicle->MechInside ) && ( Iterationcount > 1 ) ); + if( false == counted ) { continue; } if( false == vehicle->bEnabled ) { continue; } ++counts.kind[ kinds[ index ] ]; auto const *physics { vehicle->physics }; @@ -227,6 +231,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { } } auto const lap = [ & ]( std::size_t const Index, std::array &Times, std::chrono::steady_clock::time_point &Mark ) { + if( false == counted ) { return; } auto const now { std::chrono::steady_clock::now() }; if( Index < kinds.size() ) { Times[ kinds[ Index ] ].add( std::chrono::duration( now - Mark ).count() ); @@ -234,6 +239,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { Mark = now; }; for( auto const *vehicle : m_items ) { + if( false == counted ) { break; } if( false == vehicle->bEnabled ) { continue; } ++counts.enabled; if( vehicle->physics->CategoryFlag & 2 ) { ++counts.road; } @@ -288,7 +294,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { if( threads > 1 ) { counts.singlethread = "a vehicle coupled with one it doesn't see"; } - auto mark { std::chrono::steady_clock::now() }; + auto mark { counted ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point {} }; if( Iterationcount > 1 ) { // ABu: ponizsze wykonujemy tylko jesli wiecej niz jedna iteracja for( int iteration = 0; iteration < Iterationcount - 1; ++iteration ) { @@ -326,7 +332,7 @@ vehicle_table::update( double Deltatime, int Iterationcount ) { Timer::subsystem.vehicles_update.start(); { std::size_t index { 0 }; - auto mark { std::chrono::steady_clock::now() }; + auto mark { counted ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point {} }; for( auto *vehicle : m_items ) { auto const coarsestep { ( index < coarse.size() ) && ( coarse[ index ] != 0 ) }; // Ra 2015-01: tylko tu przelicza sieć trakcyjną From c529f9510fab0f2cc7c3904447af983b6554726a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 10:40:07 +0100 Subject: [PATCH 09/17] perf(logs): log.txt is flushed once for the lines of a pass of the log service LogService() flushed log.txt after every line it wrote, a WriteFile for each "EVENT LAUNCHED". It now writes the lines a pass of the service takes off the queue (every 50 ms) and flushes them once at the end of the pass, so a line is in the file at most a pass after it was logged; the last pass after the stop flushes too. A crash report takes the last lines from crashdump_note_log() as before, and errors.txt is still flushed after every line. The content of log.txt is the same. The service runs in a thread of its own, so the flushes never cost the simulation's thread: the flush/NtWriteFile on the main thread in the profile is the black box's (blackbox_recorder::update() flushing its file after every look around), which this doesn't change. 600 s in --test, seed 12345, one run each: Tomaszewo sim 133.0 s against 131.1 s the step before, L107 18.9 s against 18.5 s: within the run-to-run spread. The physics logs (14 and 9) and the event logs are byte-identical to staging's, log.txt has the same lines (only times, versions and memory figures differ), unit tests 1207/1207 with exact golden traces. --- utilities/Logs.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp index 47852be26..a918abb9f 100644 --- a/utilities/Logs.cpp +++ b/utilities/Logs.cpp @@ -141,7 +141,6 @@ void LogService() crash_signals::set_log_path(filename); } output << msg << "\n"; - output.flush(); } // log to scrollback imgui @@ -159,6 +158,11 @@ void LogService() } } + // the lines of the pass written out together, rather than one by one: at most the 50 ms of a pass after they're logged + // (and a crash report takes the last lines from crashdump_note_log() anyway) + if (output.is_open()) + output.flush(); + // --- Obsługa ErrorStack --- while (!ErrorStack.empty()) { From 0aee37599ab31f6aa6393e44803ccdc5377f2f53 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 11:07:35 +0100 Subject: [PATCH 10/17] perf(test): no sounds, smoke, wipers or mirrors in the test mode In the test mode nothing is heard or seen, yet every frame went through the sounds of the scenery and of the vehicles near the camera (basic_region::update_sounds(): the cells' sounds, TTrack:: RenderDynSounds(), TDynamicObject::RenderSounds()), the smoke (particle_manager::update()) and the wipers and the mirrors of every vehicle (updateWipers(), updateMirrors()). They're skipped there now. Checked first that none of them changes what the simulation goes by: - the sounds and the particles draw from the local engine of LocalRandom() only, which the physics, the AI and the events don't use (they draw from Random()'s engines); - RenderSounds() clears the vehicle's sound flags (ClearSoundFlags(), ClearEventFlag(), the brake's GetSoundFlag()), which nothing but the sounds reads; - the wiper positions and timers and the mirror positions are read by the renderers and the cab sounds only. Kept: updateAxleClatter(), whose joint jolts shake the physics (ShakeVertically/Horizontally). Outside the test mode nothing changes. 600 s in --test, seed 12345, one run each, the step before run again in the same session: Tomaszewo sim 129.5 s against 129.9 s, L107 17.9 s against 17.9 s: no gain shows beyond the run-to-run spread (the camera of the test mode, ghostview, has few sounds and smoke sources near it). The physics logs (14 and 9) and the event logs are byte-identical to staging's, unit tests 1207/1207 with exact golden traces. --- application/drivermode.cpp | 9 +++++++-- vehicle/dynamic/update.cpp | 7 +++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/application/drivermode.cpp b/application/drivermode.cpp index 99c3ff31e..79186a4cd 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -487,13 +487,18 @@ bool driver_mode::update() Timer::subsystem.switching.update(); Timer::subsystem.loop_audio.start(); - simulation::Region->update_sounds(); + // the test mode has no sound: the sounds of the scenery and of the vehicles aren't gone through. they draw from the local + // engine of Random() only (LocalRandom()), and clear the sound flags of the vehicles, which nothing else reads + if (false == Global.test.enabled) + simulation::Region->update_sounds(); audio::renderer.update(Global.iPause ? 0.0 : deltarealtime); Timer::subsystem.loop_audio.stop(); // NOTE: particle system runs on simulation time, but needs actual camera position to determine how to update each particle source + // nor smoke in the test mode, which draws nothing: the particles draw from the local engine of Random() only Timer::subsystem.loop_particles.start(); - simulation::Particles.update(); + if (false == Global.test.enabled) + simulation::Particles.update(); Timer::subsystem.loop_particles.stop(); Timer::subsystem.loop_renderer_update.start(); diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp index 398fe1241..a2328b958 100644 --- a/vehicle/dynamic/update.cpp +++ b/vehicle/dynamic/update.cpp @@ -159,8 +159,11 @@ bool TDynamicObject::Update(double dt, double dt1) updateWheelAngles( dt1 ); updateCurrentCollectors( dt1 ); - updateWipers( dt1 ); - updateMirrors( dt1 ); + // the wipers and the mirrors only move in the cab and make their sounds: the test mode shows and plays neither + if( false == Global.test.enabled ) { + updateWipers( dt1 ); + updateMirrors( dt1 ); + } // compartment lights // if the vehicle has a controller, we base the light state on state of the controller otherwise we check the vehicle itself From 3502ab604501dffb307482037b7100408fe78e9b Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 11:20:21 +0100 Subject: [PATCH 11/17] perf(ai): the physics log line is written with std::to_chars TController::physicslog_line() put the 26 columns of a line of physicslog/.dat through an std::ostringstream with std::fixed and std::setprecision(4): a stream, its locale facets and a printf("%.4f") (with its wctomb, fegetround and the like) for every number, ~4.4% of the main thread with the physics logs of all trains on (physicslog.trains), the most of it in std::num_put. The numbers now go through std::to_chars(fixed, 4) into the string, the integers through std::to_chars, with the same separators. printf's "%.4f" in the C locale (no locale is set anywhere) and std::to_chars both give the decimal correctly rounded to the nearest, so the text is the same: checked on 17 million doubles against snprintf("%.4f") with the same compiler and CRT, ties of the fifth decimal (multiples of 1/32 ... 1/1024, 0.00005) and values next to them included, with no difference. Infinities, NaNs (printf's inf, nan(ind)) and numbers too long for the buffer still go through snprintf("%.4f"). The floats among the values (wheel diameter, the diesel's temperatures) are written as doubles, as the stream promoted them. 600 s in --test, seed 12345, one run each, both with the physics logs of all trains: Tomaszewo sim 117.3 s against 129.5 s the step before (-9.4%); L107 16.1 s against 17.9 s (-10%). The physics logs (14 and 9) and the event logs are byte-identical to staging's, unit tests 1207/1207 with exact golden traces. --- vehicle/ai/physicslog.cpp | 103 ++++++++++++++++++++++++++------------ 1 file changed, 72 insertions(+), 31 deletions(-) diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp index 93af2a6f5..ffd4118bc 100644 --- a/vehicle/ai/physicslog.cpp +++ b/vehicle/ai/physicslog.cpp @@ -23,6 +23,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include "vehicle/Train.h" #include "vehicle/brakereleaser.h" +#include +#include +#include #include "vehicle/brakesetting.h" #include "vehicle/brakingcurve.h" #include "vehicle/fieldshunting.h" @@ -61,38 +64,76 @@ std::string_view TController::physicslog_header() { "\r\n"; } +namespace { + +// a number of the physics log as `<< std::fixed << std::setprecision( 4 )` writes it into a stream of the C locale, which +// is printf's "%.4f": std::to_chars gives the same digits, rounded to the nearest as printf rounds them, without the +// stream and the locale. infinities and NaNs (printf's inf, nan(ind)) and numbers too long for the buffer go through +// snprintf with the same format +void append_fixed( std::string &Line, double const Value ) { + char buffer[ 128 ]; + if( std::isfinite( Value ) ) { + auto const result { std::to_chars( buffer, buffer + sizeof( buffer ), Value, std::chars_format::fixed, 4 ) }; + if( result.ec == std::errc{} ) { + Line.append( buffer, result.ptr ); + return; + } + } + auto const length { std::snprintf( nullptr, 0, "%.4f", Value ) }; + std::string text( static_cast( length ) + 1, '\0' ); + std::snprintf( text.data(), text.size(), "%.4f", Value ); + text.resize( static_cast( length ) ); + Line += text; +} + +void append_int( std::string &Line, int const Value ) { + char buffer[ 16 ]; + auto const result { std::to_chars( buffer, buffer + sizeof( buffer ), Value ) }; + Line.append( buffer, result.ptr ); +} + +} // namespace + std::string TController::physicslog_line() const { - std::ostringstream line; - line << std::fixed << std::setprecision( 4 ) - << ElapsedTime << " " - << fabs(11.31 * occupied->WheelDiameter() * occupied->nrot()) << " " - << mvControlling->AccS() << " " - << occupied->Couplers[1].Dist << " " - << occupied->Couplers[1].CForce << " " - << occupied->Ft() << " " - << occupied->Ff << " " - << occupied->Fb() << " " - << occupied->brakes.cylinderPressure << " " - << occupied->brakePipe.Pressure() << " " - << mvControlling->Im << " " - << int(mvControlling->MainCtrlPos()) << " " - << int(mvControlling->ScndCtrlPos()) << " " - << occupied->brakes.HandlePositionSmooth() << " " - << occupied->brakes.IndependentPosition() << " " - << int(mvControlling->DirActive) << " " - << ( occupied->CommandIn.Text.empty() ? "none" : occupied->CommandIn.Text.c_str() ) << " " - << occupied->CommandIn.Value1 << " " - << occupied->CommandIn.Value2 << " " - << int(mvControlling->SecuritySystem.is_blinking()) << " " - << int(mvControlling->SlippingWheels()) << " " - << mvControlling->diesel.heat.Ts << " " - << mvControlling->diesel.heat.To << " " - << mvControlling->diesel.heat.temperatura1 << " " - << mvControlling->diesel.heat.temperatura2 << " " - // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid - << occupied->V() * 3.6 - << "\r\n"; - return line.str(); + // the columns of physicslog_header(), separated by spaces; the numbers as a stream with std::fixed and std::setprecision( 4 ) wrote them + std::string line; + line.reserve( 320 ); + auto const number = [ &line ]( double const Value ) { + append_fixed( line, Value ); + line += ' '; }; + auto const integer = [ &line ]( int const Value ) { + append_int( line, Value ); + line += ' '; }; + number( ElapsedTime ); + number( fabs( 11.31 * occupied->WheelDiameter() * occupied->nrot() ) ); + number( mvControlling->AccS() ); + number( occupied->Couplers[ 1 ].Dist ); + number( occupied->Couplers[ 1 ].CForce ); + number( occupied->Ft() ); + number( occupied->Ff ); + number( occupied->Fb() ); + number( occupied->brakes.cylinderPressure ); + number( occupied->brakePipe.Pressure() ); + number( mvControlling->Im ); + integer( int( mvControlling->MainCtrlPos() ) ); + integer( int( mvControlling->ScndCtrlPos() ) ); + number( occupied->brakes.HandlePositionSmooth() ); + number( occupied->brakes.IndependentPosition() ); + integer( int( mvControlling->DirActive ) ); + line += ( occupied->CommandIn.Text.empty() ? "none" : occupied->CommandIn.Text.c_str() ); + line += ' '; + number( occupied->CommandIn.Value1 ); + number( occupied->CommandIn.Value2 ); + integer( int( mvControlling->SecuritySystem.is_blinking() ) ); + integer( int( mvControlling->SlippingWheels() ) ); + number( mvControlling->diesel.heat.Ts ); + number( mvControlling->diesel.heat.To ); + number( mvControlling->diesel.heat.temperatura1 ); + number( mvControlling->diesel.heat.temperatura2 ); + // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid + append_fixed( line, occupied->V() * 3.6 ); + line += "\r\n"; + return line; } void TController::begin_physicslog() From 3be7f5e82873417afb4bc4bc8548f1318e15c263 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 30 Nov 2026 11:32:38 +0100 Subject: [PATCH 12/17] perf: the settings static without MSVC's thread-safe initialisation check Global (GetGlobalSettings()) is a function-local static, read everywhere all the time: 1.3% of the main thread was the function itself, MSVC's check of the thread-safe initialisation reading the thread's epoch from the TLS on every call. utilities/Globals.cpp is now built with /Zc:threadSafeInit- (and without the precompiled header, which is built with the default): the static is made once, by the main thread at the start, before any other thread runs, and is only read afterwards, so the plain check of the static is enough. It's the only function-local static of the file. MSVC only. 600 s in --test, seed 12345, one run each: Tomaszewo sim 115.7 s against 117.3 s the step before (-1.4%); L107 14.9 s against 16.1 s (-7%). The physics logs (14 and 9) and the event logs are byte-identical to staging's, unit tests 1207/1207 with exact golden traces. --- CMakeLists.txt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 561bbc127..166bc5107 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -483,6 +483,13 @@ set(SOURCES set(DEFINITIONS) set(SOURCES ${SOURCES} "imgui/imgui_impl_opengl3.cpp") set_source_files_properties("imgui/imgui_impl_opengl3.cpp" PROPERTIES SKIP_PRECOMPILE_HEADERS TRUE) +# the settings (Global, GetGlobalSettings()) are a function-local static read everywhere all the time: MSVC's check of its +# thread-safe initialisation reads the thread's epoch from the TLS on every call. it's made once, by the main thread, before +# any other thread starts, so the plain check of the static does; the only function-local static of the file. without the +# precompiled header, which is built with the default +if(MSVC) + set_source_files_properties("utilities/Globals.cpp" PROPERTIES COMPILE_OPTIONS "/Zc:threadSafeInit-" SKIP_PRECOMPILE_HEADERS TRUE) +endif() if (WITH_CRASHPAD) set(DEFINITIONS ${DEFINITIONS} "WITH_CRASHPAD") From 4a7eab6e136d60e33dcf083dab41e701512d5f65 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 1 Dec 2026 16:57:52 +0100 Subject: [PATCH 13/17] test: the copy of the thread's engine marked as the simulation's randomness for Sonar (S2245) --- tests/unit/test_random_engine.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/test_random_engine.cpp b/tests/unit/test_random_engine.cpp index da673ef4d..b36005d08 100644 --- a/tests/unit/test_random_engine.cpp +++ b/tests/unit/test_random_engine.cpp @@ -47,7 +47,7 @@ TEST_CASE("random engine: the lazily seeded engine draws as one seeded up front TEST_CASE("random engine: the lazy engine is seeded at the first draw only, and stands ahead of the thread's engine") { std::mt19937 threadengine{1u}; // NOSONAR: randomness of the simulation, not of anything security-relevant - auto const untouched{threadengine}; + auto const untouched{threadengine}; // NOSONAR: randomness of the simulation, not of anything security-relevant set_thread_random_engine(&threadengine); lazy_random_engine lazy; From 5b77fed81f7f464579f1661b47c99fdb0ec3dc2e Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 1 Dec 2026 16:57:52 +0100 Subject: [PATCH 14/17] perf: the settings static back with MSVC's thread-safe initialisation check Takes back 3be7f5e82. /Zc:threadSafeInit- on utilities/Globals.cpp drops the guard from every function-local static compiled in that file, those of the inline and template functions of stdafx.h and the project's headers included, and the linker may keep that file's copy of such a function for the whole program. The 1.4% it gave in one run is inside the run-to-run noise, so a static put in a header later and used from two threads isn't worth the risk. Globals.cpp is built with the precompiled header again. --- CMakeLists.txt | 7 ------- 1 file changed, 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 166bc5107..561bbc127 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -483,13 +483,6 @@ set(SOURCES set(DEFINITIONS) set(SOURCES ${SOURCES} "imgui/imgui_impl_opengl3.cpp") set_source_files_properties("imgui/imgui_impl_opengl3.cpp" PROPERTIES SKIP_PRECOMPILE_HEADERS TRUE) -# the settings (Global, GetGlobalSettings()) are a function-local static read everywhere all the time: MSVC's check of its -# thread-safe initialisation reads the thread's epoch from the TLS on every call. it's made once, by the main thread, before -# any other thread starts, so the plain check of the static does; the only function-local static of the file. without the -# precompiled header, which is built with the default -if(MSVC) - set_source_files_properties("utilities/Globals.cpp" PROPERTIES COMPILE_OPTIONS "/Zc:threadSafeInit-" SKIP_PRECOMPILE_HEADERS TRUE) -endif() if (WITH_CRASHPAD) set(DEFINITIONS ${DEFINITIONS} "WITH_CRASHPAD") From 2883887f5c5629b777f61a88d6d7f327adbff9ae Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 1 Dec 2026 16:58:29 +0100 Subject: [PATCH 15/17] perf(physics): the trains of the hose exchange kept by the vehicle table, the inputs of a step read into kept storage The cache of the trains was a function-local static of vehicle_table::update_brake_pipes(), shared by every vehicle_table and kept from one scenery to the next; it's now a member next to m_brakepipes, the list it is for. The inputs of each step were read into a new vector, twice per step (the brake and the main reservoir pipe); they're now read into scratch storage of the cache, swapped with the kept inputs when they differ. --- physics/components/hosetrains.h | 1 + physics/components/pneumatics.cpp | 7 +++---- vehicle/DynObj.h | 3 +++ vehicle/dynamic/vehicletable.cpp | 4 +--- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/physics/components/hosetrains.h b/physics/components/hosetrains.h index 64cd66250..1eafce24e 100644 --- a/physics/components/hosetrains.h +++ b/physics/components/hosetrains.h @@ -39,6 +39,7 @@ class hose_trains_cache struct pipe { std::vector inputs; + std::vector scratch; // the inputs of the step, read in to be compared with those, kept for the memory std::vector trains; // the train of each vehicle of the list, none for one which didn't step the pipe std::vector firsts; // train t is members[firsts[t]] up to members[firsts[t + 1]], not included std::vector members; // the indices in the list of the vehicles of each train, in the order of the list diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp index 0bf68e90b..cd85345ae 100644 --- a/physics/components/pneumatics.cpp +++ b/physics/components/pneumatics.cpp @@ -1493,12 +1493,11 @@ void exchange_through_hoses(std::vector const &Vehicles, tra auto *layout{&fresh}; if (Cache != nullptr) { - std::vector inputs; - hose_inputs(inputs, Vehicles, trainPipe); - if (false == Cache->valid || inputs != Cache->inputs) + hose_inputs(Cache->scratch, Vehicles, trainPipe); + if (false == Cache->valid || Cache->scratch != Cache->inputs) { lay_out_trains(*Cache, hose_trains(Vehicles, trainPipe)); - Cache->inputs = std::move(inputs); + std::swap(Cache->inputs, Cache->scratch); Cache->valid = true; } layout = Cache; diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index adf70bb18..09675e02a 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "physics/vehicletypes.h" #include "physics/derailment.h" #include "physics/consistbraking.h" +#include "physics/components/hosetrains.h" #include "vehicle/derailmotion.h" #include "world/TrkFoll.h" #include "vehicle/Button.h" @@ -1151,6 +1152,8 @@ private: double m_overlapdue { 1.0 }; bool m_overlaplogged { false }; std::vector m_brakepipes; // the vehicles of update_brake_pipes(), kept for the memory + // the trains of the hoses of m_brakepipes, which change seldom: kept from one step to the next while they stay + physics::hose_trains_cache m_hosetrains; std::vector> m_offtrackterrains; // of off_track_terrain() }; diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp index 82a06fe66..95ab872e1 100644 --- a/vehicle/dynamic/vehicletable.cpp +++ b/vehicle/dynamic/vehicletable.cpp @@ -575,9 +575,7 @@ vehicle_table::update_brake_pipes( double const Deltatime ) { m_brakepipes.push_back( vehicle->physics ); } } - // the trains of the hoses of all the vehicles change seldom, they're kept from one step to the next while they stay - static physics::hose_trains_cache hosetrains; - physics::UpdatePipeCouplers( m_brakepipes, Deltatime, hosetrains ); + physics::UpdatePipeCouplers( m_brakepipes, Deltatime, m_hosetrains ); } // records the odometer states of the vehicles and saves them for the next sessions (eu07/maszyna#72) From ecf524063e0bb453841a5ff0ddabb6c25bfd99f8 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 1 Dec 2026 16:59:35 +0100 Subject: [PATCH 16/17] refactor: std::array for the buffers of the physics log line and the seed of the lazy engine, ownP in the if Sonar's remarks on the new code of this branch: the C arrays of append_fixed(), append_int() and lazy_random_engine are std::arrays (S5945), the pressure of the ESt3 relays read once is declared in the if that uses it (S6004), and the thread_local pointer to the lazy engine has the NOSONAR of the one above it. The snprintf of the infinities and NaNs of the physics log stays, with a NOSONAR: std::format writes them otherwise than printf's inf and nan(ind). No change of what the code does. --- physics/oerlikonest.cpp | 10 +++------- utilities/lazyrandom.h | 3 ++- utilities/utilities.cpp | 2 +- vehicle/ai/physicslog.cpp | 17 +++++++++-------- 4 files changed, 15 insertions(+), 17 deletions(-) diff --git a/physics/oerlikonest.cpp b/physics/oerlikonest.cpp index 4eab8d582..524624a21 100644 --- a/physics/oerlikonest.cpp +++ b/physics/oerlikonest.cpp @@ -67,9 +67,7 @@ void TPrzekladnik::Update(double dt) double BCP{ Next->P() }; double BVP{ BrakeRes->P() }; // the pressure of the relay itself, read once: nothing changes it before the flows are applied (Act()) - double const ownP{ P() }; - - if ( BCP > ownP ) + if ( double const ownP{ P() }; BCP > ownP ) dV = -PFVd(BCP, 0, d2A(10), ownP) * dt; else { if( BCP < ownP ) @@ -122,8 +120,7 @@ void TRapid::Update(double dt) ActMult = 1.0; } - double const ownP{ P() }; - if (BCP * RapidMult > ownP * ActMult) + if (double const ownP{ P() }; BCP * RapidMult > ownP * ActMult) dV = -PFVd(BCP, 0, DL, ownP * ActMult / RapidMult) * dt; else if (BCP * RapidMult < ownP * ActMult) dV = PFVa(BVP, BCP, DN, ownP * ActMult / RapidMult) * dt; @@ -148,8 +145,7 @@ void TPrzekCiagly::Update(double dt) double const BCP{ Next->P() }; double dV; - double const ownP{ P() }; - if ( BCP > ownP * Mult) + if ( double const ownP{ P() }; BCP > ownP * Mult) dV = -PFVd(BCP, 0, d2A(8.0), ownP * Mult) * dt; else if (BCP < ownP * Mult) dV = PFVa(BVP, BCP, d2A(8.0), ownP * Mult) * dt; diff --git a/utilities/lazyrandom.h b/utilities/lazyrandom.h index aed55184b..c55ebedd5 100644 --- a/utilities/lazyrandom.h +++ b/utilities/lazyrandom.h @@ -13,13 +13,14 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include #include struct lazy_random_engine { - std::uint32_t seed[2]{}; + std::array seed{}; std::optional engine; // NOSONAR: randomness of the simulation, not of anything security-relevant }; diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 8b7c3868b..d38e4baa0 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -182,7 +182,7 @@ bool ClearFlag(int &Flag, int const Value) namespace { thread_local std::mt19937 *t_random_engine{nullptr}; // NOSONAR: randomness of the simulation, not of anything security-relevant -thread_local lazy_random_engine *t_lazy_random_engine{nullptr}; +thread_local lazy_random_engine *t_lazy_random_engine{nullptr}; // NOSONAR: randomness of the simulation, not of anything security-relevant std::mt19937 &random_engine() // NOSONAR: randomness of the simulation, not of anything security-relevant { diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp index ffd4118bc..d7aff2512 100644 --- a/vehicle/ai/physicslog.cpp +++ b/vehicle/ai/physicslog.cpp @@ -23,6 +23,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include "vehicle/Train.h" #include "vehicle/brakereleaser.h" +#include #include #include #include @@ -71,25 +72,25 @@ namespace { // stream and the locale. infinities and NaNs (printf's inf, nan(ind)) and numbers too long for the buffer go through // snprintf with the same format void append_fixed( std::string &Line, double const Value ) { - char buffer[ 128 ]; + std::array buffer; if( std::isfinite( Value ) ) { - auto const result { std::to_chars( buffer, buffer + sizeof( buffer ), Value, std::chars_format::fixed, 4 ) }; + auto const result { std::to_chars( buffer.data(), buffer.data() + buffer.size(), Value, std::chars_format::fixed, 4 ) }; if( result.ec == std::errc{} ) { - Line.append( buffer, result.ptr ); + Line.append( buffer.data(), result.ptr ); return; } } - auto const length { std::snprintf( nullptr, 0, "%.4f", Value ) }; + auto const length { std::snprintf( nullptr, 0, "%.4f", Value ) }; // NOSONAR: printf's own text of inf and NaN, which std::format writes otherwise std::string text( static_cast( length ) + 1, '\0' ); - std::snprintf( text.data(), text.size(), "%.4f", Value ); + std::snprintf( text.data(), text.size(), "%.4f", Value ); // NOSONAR: printf's own text of inf and NaN, which std::format writes otherwise text.resize( static_cast( length ) ); Line += text; } void append_int( std::string &Line, int const Value ) { - char buffer[ 16 ]; - auto const result { std::to_chars( buffer, buffer + sizeof( buffer ), Value ) }; - Line.append( buffer, result.ptr ); + std::array buffer; + auto const result { std::to_chars( buffer.data(), buffer.data() + buffer.size(), Value ) }; + Line.append( buffer.data(), result.ptr ); } } // namespace From a1a988d7537374536ac671673685ef0faf8cbd4a Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Tue, 1 Dec 2026 17:28:55 +0100 Subject: [PATCH 17/17] test: the trains of the hose exchange kept from one step to the next against ones worked out in every step One train, a locomotive with five freight wagons on a gradient, stepped twice from the same seed: as the game steps it, the trains of the hoses kept in the cache, and with them worked out again in every step (test::consist::keep_hose_trains(false)). Charged, braked, the last two wagons uncoupled, released: with Global.physics_sleepheld the wagons held by their brakes fall asleep and wake on the way, so the trains change with the uncoupling and with the vehicles going to sleep and waking. The pipes, the reservoirs of the hoses and the brake cylinders of the two are bitwise the same after every step. A cache which is never laid out again after its first step fails it (10203 differences). --- tests/unit/consist.cpp | 7 ++- tests/unit/consist.h | 5 +++ tests/unit/test_brake_pipe.cpp | 82 ++++++++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 1 deletion(-) diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index d6d0f1a41..0cd0c1063 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -100,7 +100,12 @@ void consist::update_brake_pipes(double Dt) const { for (auto const &vehicle : m_vehicles) { vehicles.push_back(&vehicle->physics()); } - physics::UpdatePipeCouplers(vehicles, Dt, m_hosetrains); + if (m_keephosetrains) { + physics::UpdatePipeCouplers(vehicles, Dt, m_hosetrains); + } + else { + physics::Vehicle::UpdatePipeCouplers(vehicles, Dt); + } } void consist::run(double Seconds, track const &Track, double Dt) { diff --git a/tests/unit/consist.h b/tests/unit/consist.h index 7d2cbbd69..2131bba2d 100644 --- a/tests/unit/consist.h +++ b/tests/unit/consist.h @@ -44,6 +44,10 @@ public: // distance between the couplers of the vehicle and the one behind it [m], negative when the buffers press double gap(std::size_t Index) const; + // whether the trains of the hose exchange are kept from one step to the next, as the game keeps them (the default), or + // worked out again in every step + void keep_hose_trains(bool Keep) { m_keephosetrains = Keep; } + private: void update_neighbours(); void update_brake_pipes(double Dt) const; @@ -56,6 +60,7 @@ private: std::vector> m_objects; // the trains of the hoses kept from one step to the next, as vehicle_table::update_brake_pipes() keeps them mutable physics::hose_trains_cache m_hosetrains; + bool m_keephosetrains{true}; }; } // namespace test diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp index e1281992b..66026591e 100644 --- a/tests/unit/test_brake_pipe.cpp +++ b/tests/unit/test_brake_pipe.cpp @@ -3,9 +3,15 @@ #include "physics/vehicle.h" #include "physics/brakes.h" +#include "utilities/Globals.h" +#include "utilities/utilities.h" #include "consist.h" #include "vehicle.h" +#include +#include +#include + // the air exchange through the brake hoses between the vehicles of a train (physics::Vehicle::UpdatePipeCouplers()). // taken in one explicit step of 0.01 s, the hose between two short freight wagons carried twice the air which evens // out their pipes: the pipes overshot each other in turns, and an ESt3 distributor saw the pipe pressure up to @@ -116,3 +122,79 @@ TEST_CASE("brake pipe: a passenger train, whose exchange was stable in one step, CAPTURE(usual); CHECK(usual == doctest::Approx(converged).epsilon(0.05)); } + +namespace { + +// Global.physics_sleepheld, off by default, on for the test it's made in +struct sleepheld_on { + bool const was{Global.physics_sleepheld}; + sleepheld_on() { Global.physics_sleepheld = true; } + ~sleepheld_on() { Global.physics_sleepheld = was; } + sleepheld_on(sleepheld_on const &) = delete; + sleepheld_on &operator=(sleepheld_on const &) = delete; +}; + +} // namespace + +TEST_CASE("brake pipe: the trains of the hose exchange kept from one step to the next come out as worked out in every step") { + // a locomotive with five freight wagons on a gradient, charged and braked; the last two wagons uncoupled, then the train + // released. with Global.physics_sleepheld the wagons held by their brakes fall asleep and wake on the way (a vehicle + // asleep doesn't step its pipe, so it ends the trains of the hoses), and the uncoupling splits a train in two + sleepheld_on const sleepheld; + test::track slope; + slope.gradient = 0.01; + auto const build = [](test::consist &Train) { + Train.add(definition::fiz("st44_v2/m62-1151")); + for (int i = 0; i < 5; ++i) { + Train.add(definition::fiz("3wl_v2/3wl")); + } + Train[0].hold_brake_pipe(5.0); + }; + // each train with an engine of its own for the draws of its physics, seeded alike + std::mt19937 keptdraws{12345}; // NOSONAR: randomness of the simulation, not of anything security-relevant + std::mt19937 freshdraws{12345}; // NOSONAR: randomness of the simulation, not of anything security-relevant + test::consist kept; + test::consist fresh; + fresh.keep_hose_trains(false); + auto const both = [&keptdraws, &freshdraws, &kept, &fresh](auto const &Action) { + set_thread_random_engine(&keptdraws); + Action(kept); + set_thread_random_engine(&freshdraws); + Action(fresh); + set_thread_random_engine(nullptr); + }; + both(build); + // the vehicles which came out of a step differing between the two trains, and the times a vehicle fell asleep or woke + int differing{0}; + int sleeps{0}; + int wakes{0}; + std::vector awake(kept.size(), true); + auto const run = [&both, &slope, &kept, &fresh, &differing, &sleeps, &wakes, &awake](double const Seconds) { + for (auto step = std::lround(Seconds / 0.01); step > 0; --step) { + both([&slope](test::consist &Train) { Train.step(slope); }); + for (std::size_t i = 0; i < kept.size(); ++i) { + auto const &a{kept[i].physics()}; + auto const &b{fresh[i].physics()}; + if (a.brakePipe.Pressure() != b.brakePipe.Pressure() || a.brakePipe.reservoir->P() != b.brakePipe.reservoir->P() || + a.mainPipe.Pressure() != b.mainPipe.Pressure() || a.mainPipe.reservoir->P() != b.mainPipe.reservoir->P() || + a.brakes.cylinderPressure != b.brakes.cylinderPressure) { + ++differing; + } + if (awake[i] != a.PhysicActivation()) { + ++(a.PhysicActivation() ? wakes : sleeps); + awake[i] = a.PhysicActivation(); + } + } + } + }; + run(60.0); + both([](test::consist &Train) { Train[0].hold_brake_pipe(3.5); }); + run(30.0); + both([](test::consist &Train) { REQUIRE(Train[3]->Dettach(VehicleEnd::rear)); }); + run(60.0); + both([](test::consist &Train) { Train[0].hold_brake_pipe(5.0); }); + run(60.0); + CHECK(differing == 0); + CHECK(sleeps > 0); + CHECK(wakes > 0); +}